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

c# entity-framework entity-framework-6 linq

Question

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.

1
2
12/22/2015 12:25:50 PM

Accepted Answer

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.

7
12/22/2015 12:41:17 PM

Popular Answer

try

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow