簡體   English   中英

C# - Linq:無法創建類型的常量值在此上下文中僅支持基本類型或枚舉類型。

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

我正在使用此linq查詢進行登錄

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

但在執行中拋出此異常:

EntityFramework.SqlServer.dll中出現未處理的“System.NotSupportedException”類型異常

附加信息:無法創建“MyProject.MyModels.Person_Login”類型的常量值。 在此上下文中僅支持基元類型或枚舉類型。

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

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左外連接。

嘗試

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

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM