成员“在LINQ to Entities中不受支持”
所以我是C#,LINQ和MVC的新手。 我试图得到一个年龄列表,但它说
LINQ to Entities不支持指定的类型成员’Age’。 仅支持初始化程序,实体成员和实体导航属性。
对于之前的教程,他们使用这个完全相同的逻辑,除了他们检查字符串,而不是int(年龄)。 为什么这会让我感到健康,我该如何解决?
public ActionResult SearchIndex(string ageValue, string searchString) { if (!string.IsNullOrEmpty(ageValue)) { var AgeList = new List(); var AgeListQry = from d in db.Actors orderby d.Age select d.Age.ToString(); AgeList.AddRange(AgeListQry.Distinct()); } // other stuff }
我想知道发生了什么,以便将来可以避免这种情况!
实体模型代码
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 Actors { get; set; } }
如评论中所述,您无法在Linq to Entities查询中调用ToString()
。 而是这样做:
var AgeList = new List(); //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());
编辑
我看到您的最新更新确实显示Age
不是数据库列。 然后你需要做这样的事情(假设BirthDate
被正确映射):
var AgeList = new List(); //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());
Linq to Entities将表达式映射到SQL语句,并且在使用Age
属性时没有任何内容可以映射到它。 相反,您需要从SQL Server( BirthDate
)中获取所需内容,然后BirthDate
翻译为Age。 如果您愿意,可以使用这样的方法调用替换内联代码:
AgeList.AddRange(AgeListQry.Select(bd => CalculateAge(bd)).Distinct()); //... private string CalculateAge(DateTime birthday) { return ((int)(DateTime.Now - bd).TotalDays / 365).ToString(); }
您没有DB
方案中的Age
,也无法将LINQ
转换为DB查询。 您必须在客户端订购Age
集合或将计算列添加到表中。