3

我有 2 张桌子:CustomerCustomer_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 不是 aIEnumerable(Customer_Address)因为它有Customer字段 ( cust.Name)

我怎么解决这个问题 ?

4

4 回答 4

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();
于 2012-07-23T19:30:10.417 回答
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;
}
于 2012-07-23T19:29:06.430 回答
1

@Daniel DiPaolo 建议的解决方案很好,他在其中声明了一个轻量级来保存您想要的唯一属性,但我认为使用属性而不是字段更好,如下所示:

class CustomerInfo   // new class
{
    public string CustomerName{get;set;}
    public string CustomerAddress{get;set;}
    public string CustomerTel{get;set;}
}
于 2012-07-27T07:58:44.023 回答
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;
于 2012-07-23T19:30:57.567 回答