我有两张桌子:Customer
和Customer_Address
我有一个功能:
public IEnumerable<Customer_Address> ReadAddressForCustomer(int CustomerID)
{
ProjectServiceForCustomerDataContext DB = new ProjectServiceForCustomerDataContext();
var CA = (from C in DB.Customer_Addresses
join cust in DB.Customers
on C.CustomerID equals cust.ID
where C.CustomerID == CustomerID
select new
{
CustomerName=cust.Name,
CustomerAddress=C.Address,
CustomerTel=C.Telephone
}).ToList();
return CA;
}
但CA不是IEnumerable(Customer_Address)
,因为它有Customer
字段(cust.Name
)
我该如何解决这个问题?
答案 0 :(得分:5)
您返回匿名类型,这就是为什么它不是IEnumerable<Customer_Address>
尝试使用与此相似的内容
var CA = (from C in DB.Customer_Addresses
join cust in DB.Customers
on C.CustomerID equals cust.ID
where C.CustomerID == CustomerID
select new Customer_Address( // <--- HERE
cust.Name,
C.Address,
C.Telephone
).ToList();
答案 1 :(得分:1)
创建一个封装所需数据的新具体类型:
class CustomerInfo // new class
{
private string CustomerName;
private string CustomerAddress;
private string CustomerTel;
}
public IEnumerable<CustomerInfo> ReadAddressForCustomer(int CustomerID) //return new class
{
ProjectServiceForCustomerDataContext DB = new ProjectServiceForCustomerDataContext();
var CA = from C in DB.Customer_Addresses
join cust in DB.Customers
on C.CustomerID equals cust.ID
where C.CustomerID == CustomerID
select new CustomerInfo // instantiate new concrete type
{
CustomerName=cust.Name,
CustomerAddress=C.Address,
CustomerTel=C.Telephone
} // don't call ToList anymore
return CA;
}
答案 2 :(得分:1)
@Daniel DiPaolo提出的解决方案很好,他声明了一个轻量级来保存你想要的唯一属性,但我认为最好使用属性而不是字段,如下所示:
class CustomerInfo // new class
{
public string CustomerName{get;set;}
public string CustomerAddress{get;set;}
public string CustomerTel{get;set;}
}
答案 3 :(得分:0)
你也可以施展它
Enumerable<CustomerInfo> CA =
fruits.Cast<CustomerInfo>().(from C in DB.Customer_Addresses
join cust in DB.Customers
on C.CustomerID equals cust.ID
where C.CustomerID == CustomerID
select new
{
CustomerName=cust.Name,
CustomerAddress=C.Address,
CustomerTel=C.Telephone
}
);
return CA;