我的代码如下面的服务器端:
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;
}
但是当我运行项目时,会显示以下错误:
无法在LINQ中构造实体或复杂类型“CUSTOMER” 到实体查询。
答案 0 :(得分:2)
假设Customer是映射实体,则无法在Entity Framework中对Customer类进行预测。相反,你可以试试这个:
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 };
}
此查询使用匿名类型进行投影。之后,您可以将匿名类型映射到Customer类型的实例。
或者,您可以使用不属于DbContext的类来进行投影(使用所谓的DTO):
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;
}
注意这里的类是如何不同的(假设CUSTOMERDTO未在Entity Framework运行时中声明。
答案 1 :(得分:0)
不CUSTOMER()
你必须写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;
但已经结果是客户你可以像这样写
var customerInfo = db.CUSTOMER.Where(c => c.CUSTOMERNUMBER == customerNumber).SingleOrDefault();