0

私のテーブルPersonsには、という名前の生年月日列がありますDOB

私の dbml ファイルに、singleという名前の追加のプロパティを追加しましたAge

AgeLinq クエリで、今日の ad から計算された年齢を返すにはどうすればよいDOBですか? つまり、以下の架空のコードのようなものを実現するにはどうすればよいですか。

 DataClasses1 db = new DataClasses1();
 var pp = from p in db.Persons
       select new Person()
                   {  
                      Name = p.Name, // ... clone all the other properties ...
                      Age = (DateTime.Today-p.DOB).Days/365
                   }

同じ目的を達成する別の方法はありますか?

ありがとう。

4

1 に答える 1

2

プロパティに年齢計算ロジックを配置しAge、データベースから生年月日のみをダウンロードできます。

public int Age 
{
   get { 
      DateTime today = DateTime.Today;
      int age = today.Year - DOB.Year;
      if (DOB > today.AddYears(-age)) age--;
      return age;
   }
}

サーバー側で年齢を計算する場合 (質問のタグによると、これは LINQ to SQL コードです):

from p in db.Persons
let age = SqlMethods.DateDiffYear(p.DOB, DateTime.Today)
select new Person {  
    Name = p.Name,
    Age = SqlMethods.DateDiffDay(DateTime.Today.AddYears(-age), p.DOB) > 0 ? 
              age - 1 : age
}
于 2013-03-13T16:36:18.437 に答える