简体   繁体   中英

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

I am using this linq query for login

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

but in execution throw this exception:

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.

The exception message is quite descriptive.

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

is not supported in Linq to Entities.

You can use the following instead

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

Note that DefaultIfEmpty method is used mainly for performing LINQ left outer joins.

try

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

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM