C#-Linq : Unable to create a constant value of type Only primitive types or enumeration types are supported in this context.

标签 c# entity-framework linq entity-framework-6

我正在使用此 linq 查询进行登录

var login = context.Person_Login
                   .Where(c => c.Username == username && c.Password == password)
                   .DefaultIfEmpty(new Person_Login({Id = -1})
                   .First();

但是在执行中抛出这个异常:

An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll

Additional information: Unable to create a constant value of type 'MyProject.MyModels.Person_Login'. Only primitive types or enumeration types are supported in this context.

最佳答案

异常消息非常具有描述性。

DefaultIfEmpty(new Person_Login({Id = -1}))

在 Linq to Entities 中不受支持。

你可以用下面的代替

var login = context.Person_Login
    .FirstOrDefault(c => c.Username == username && c.Password == password)
    ?? new Person_Login {Id = -1};

请注意,DefaultIfEmpty 方法主要用于执行 LINQ 左外连接。

关于C#-Linq : Unable to create a constant value of type Only primitive types or enumeration types are supported in this context.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34415910/

相关文章:

c# - 在 C# 中获取启动快捷方式

c# - LINQ 语句生成与 LinqPad 不同的查询

C#:为什么我的 SQL 查询中缺少 .Where() 条件之一?

c# 使用 Tuple 对 List<> 进行排序?

c# - 如何将字符串拆分为有效的方式c#

c# - 从另一个类中的另一个线程更新文本框内容。 C#、WPF

c# - 在获取父实体 EFCore 时加载子实体

c# - 添加迁移失败,因为未安装 EntityFrameworkCore.Tools

visual-studio-2008 - Visual Studio 2008 是否有一个插件可以让您在监 window 口中使用 Linq?

c# - 如何获取作为另一个元素后代的多个 XML 元素