gpt4 book ai didi

c# - 成员是 "not supported in LINQ to Entities"

转载 作者:太空狗 更新时间:2023-10-30 00:19:13 26 4
gpt4 key购买 nike

所以我是 C#、LINQ 和 MVC 的新手。我正在尝试获取年龄列表,但上面写着

The specified type member 'Age' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

对于之前的教程,他们使用完全相同的逻辑,除了他们检查的是字符串,而不是 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
}

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

实体模型代码

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; }
}

最佳答案

如评论中所述,您不能在 Linq to Entities 查询中调用 ToString()。而是这样做:

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());

编辑

我看到您的最新更新显示 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());

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();
}

关于c# - 成员是 "not supported in LINQ to Entities",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23665150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com