Reputation: 33
My code is like below on the server side:
public CUSTOMER GetCustomerByNumber(string customerNumber){
var customerInfo = (from c in db.CUSTOMER
where c.CUSTOMERNUMBER == customerNumber
select new CUSTOMER()
{
Id = c.Id,
FirstName = c.FirstName,
LastName = c.LastName
}).SingleOrDefault();
return customerInfo;
}
but when I run the project the following error is shown:
The entity or complex type 'CUSTOMER' cannot be constructed in a LINQ to Entities query.
Upvotes: 2
Views: 62
Reputation: 4082
Not CUSTOMER()
You have to write Customer
public CUSTOMER GetCustomerByNumber(string customerNumber){
var customerInfo = (from c in db.CUSTOMER
where c.CUSTOMERNUMBER == customerNumber
select new CUSTOMER // HERE
{
Id = c.Id,
FirstName = c.FirstName,
LastName = c.LastName
}).SingleOrDefault();
return customerInfo;
But already result is Customer You can write like this
var customerInfo = db.CUSTOMER.Where(c => c.CUSTOMERNUMBER == customerNumber).SingleOrDefault();
Upvotes: 0
Reputation: 1969
Projections on the Customer class is not possible in Entity Framework, assuming Customer is a mapped entity. Instead, you can try this:
public CUSTOMER GetCustomerByNumber(string customerNumber){
var customerInfo = (from c in db.T_CLUB_CUSTOMER
where c.C_CUSTOMER_NUMBER == customerNumber
select new
{
Id = c.Id,
D_DEFINE = c.D_DEFINE,
B_IS_REAL = c.B_IS_REAL,
C_NATIONAL_CODE = c.C_NATIONAL_CODE
}).SingleOrDefault();
return new Customer() { Id = customerInfo.Id };
}
This query uses an anonymous type to do the projection. Afterwards you can map the anonymous type to an instance of your Customer type.
Alternatively, you can use a class that is not part of your DbContext to do the projection (using so called DTOs):
public CUSTOMERDTO GetCustomerByNumber(string customerNumber){
var customerInfo = (from c in db.T_CLUB_CUSTOMER
where c.C_CUSTOMER_NUMBER == customerNumber
select new CUSTOMERDTO
{
Id = c.Id,
D_DEFINE = c.D_DEFINE,
B_IS_REAL = c.B_IS_REAL,
C_NATIONAL_CODE = c.C_NATIONAL_CODE
}).SingleOrDefault();
return customerInfo;
}
Notice how the class is different here (assuming CUSTOMERDTO is not declared in the Entity Framework runtime.
Upvotes: 2