服务器端的代码如下:
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;
}
但是当我运行项目时显示以下错误:
实体或复杂类型'CUSTOMER'不能在LINQ中构造to Entities查询
在实体框架中不可能对Customer类进行投影,假设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没有在实体框架运行时中声明)。
不是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;
但是结果已经是Customer了,你可以这样写
var customerInfo = db.CUSTOMER.Where(c => c.CUSTOMERNUMBER == customerNumber).SingleOrDefault();