c# - 无法创建类型的常量值在此上下文中仅支持原始类型或枚举类型

标签 c# linq entity-framework join

我收到以下查询的错误

Unable to create a constant value of type API.Models.PersonProtocol. Only primitive types or enumeration types are supported in this context

下面的

ppCombined是一个PersonProtocolTypeIEnumerable对象,由2个PersonProtocol列表拼接而成。

为什么会失败?我们不能在 JOINSELECT 中使用 LINQ JOIN 子句吗?

var persons = db.Favorites
    .Where(x => x.userId == userId)
    .Join(db.Person, x => x.personId, y => y.personId, (x, y) =>
        new PersonDTO
        {
            personId = y.personId,
            addressId = y.addressId,                   
            favoriteId = x.favoriteId,
            personProtocol = (ICollection<PersonProtocol>) ppCombined
                .Where(a => a.personId == x.personId)
                .Select( b => new PersonProtocol()
                 {
                     personProtocolId = b.personProtocolId,
                     activateDt = b.activateDt,
                     personId = b.personId
                 })
        });

最佳答案

这是行不通的,因为 ppCombined 是内存中对象的集合,您不能将数据库中的一组数据与内存中的另一组数据连接起来。在从数据库中检索到其他属性后,您可以尝试在内存中提取ppCombined 集合的过滤项personProtocol::

var persons = db.Favorites
    .Where(f => f.userId == userId)
    .Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
        new // anonymous object
        {
            personId = p.personId,
            addressId = p.addressId,   
            favoriteId = f.favoriteId,
        })
    .AsEnumerable() // database query ends here, the rest is a query in memory
    .Select(x =>
        new PersonDTO
        {
            personId = x.personId,
            addressId = x.addressId,   
            favoriteId = x.favoriteId,
            personProtocol = ppCombined
                .Where(p => p.personId == x.personId)
                .Select(p => new PersonProtocol
                {
                    personProtocolId = p.personProtocolId,
                    activateDt = p.activateDt,
                    personId = p.personId
                })
                .ToList()
        });

关于c# - 无法创建类型的常量值在此上下文中仅支持原始类型或枚举类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18929483/

相关文章:

c# - SqlDataReader 显示 InvalidCastException(C# Windows 窗体)

c# - ASP.NET : EF 5. X - 访问级别错误

c# - 如何使用 Entity Framework 调用标量值函数并获取结果

c# - ToList()、Any()、Count()、Sum() 上的 Linq 错误

c# - .NET 和 P2P - 编写 P2P 信使

c# - LINQ 将多个 IEnumerables 聚合为一个?

linq - 编译 NHibernate Linq 表达式

sql - 使用 DbSet<T>.SqlQuery() 时,如何使用命名参数?

c# - 通用检查 Entity Framework 和存储库模式是否发生了变化

c# - Entity Framework 延迟加载不起作用