成员"在LINQ to Entities中不受支持"

Aus*_*tin 4 c# linq linq-to-entities entity-framework

所以我是C#,LINQ和MVC的新手.我试图得到一个年龄列表,但它说

LINQ to Entities不支持指定的类型成员'Age'.仅支持初始值设定项,实体成员和实体导航属性.

对于之前的教程,他们使用这个完全相同的逻辑,除了他们检查字符串,而不是int(Age).为什么这给了我一个合适的,我该如何解决它?

public ActionResult SearchIndex(string ageValue, string searchString)
{
    if (!string.IsNullOrEmpty(ageValue))
    {
         var AgeList = new List<string>();
         var AgeListQry = from d in db.Actors orderby d.Age select d.Age.ToString();
         AgeList.AddRange(AgeListQry.Distinct());
    }
    // other stuff
}
Run Code Online (Sandbox Code Playgroud)

我想知道发生了什么,以便将来可以避免这种情况!

实体模型代码

public class Actor
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public DateTime BirthDate { get; set; }
        public int Age
        {
            get { 
                return (int)(DateTime.Now - BirthDate).TotalDays / 365; 
            }

        }
        public decimal NetValue { get; set; }
    }
    public class ActorDBContext : DbContext
    {
        public DbSet<Actor> Actors { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

Sve*_*sen 9

如评论中所述,您无法调用ToString()Linq to Entities查询.而是这样做:

var AgeList = new List<string>();
//retrieve as whatever type Age is, no conversion in SQL Server
var AgeListQry = (from d in db.Actors orderby d.Age select d.Age).ToList();
//convert them after the fact, using Linq to Objects
AgeList.AddRange(AgeListQry.Select(a => a.ToString()).Distinct());
Run Code Online (Sandbox Code Playgroud)

编辑

我看到了您的最新更新,确实显示该Age数据库不是数据库列.然后,您需要执行以下操作(假设BirthDate已正确映射):

var AgeList = new List<string>();
//retrieve BirthDate from SQL Server and use ToList() to get it to run immediately
var AgeListQry = (from d in db.Actors orderby d.BirthDate select d.BirthDate).ToList();
//convert them after the fact, using Linq to Objects
AgeList.AddRange(AgeListQry.Select(bd => ((int)(DateTime.Now - bd).TotalDays / 365).ToString()).Distinct());
Run Code Online (Sandbox Code Playgroud)

Linq to Entities将您的表达式映射到SQL语句,并且在您使用Age属性时没有任何内容可以映射到它们.相反,您需要从SQL Server(BirthDate)中获取所需内容,然后自行完成对Age的转换.如果你愿意,你可以用这样的方法调用替换内联代码:

AgeList.AddRange(AgeListQry.Select(bd => CalculateAge(bd)).Distinct());
//...
private string CalculateAge(DateTime birthday)
{
   return ((int)(DateTime.Now - bd).TotalDays / 365).ToString();
}
Run Code Online (Sandbox Code Playgroud)