我有一个Entity Framework模型,其中有一个“Customers”和一个“CustomerPhones”表。客户可以拥有多个电话号码,因此“客户”实体具有“电话”集合。我可以毫无问题地查询模型:
using (CustomerEntities context = new CustomerEntities())
{
Customer customer = context.Customers.FirstOrDefault();
CustomerPhone phone = customer.Phones.FirstOrDefault();
MessageBox.Show(customer.Name + " " + phone.Number);
}
这个模型对于我需要做的事情太复杂了(尽管我的例子是基本的)所以我试图把它归结为更简单的POCO。以下是两个简单的类:
public class SimplePhone
{
public int Id { get; set; }
public string Number { get; set; }
}
public class SimpleCustomer
{
public int Id { get; set; }
public string Name { get; set; }
//Phones is a list because a single Customer can have multiple phone numbers
public List<SimplePhone> Phones { get; set; }
}
我可以使用“IQueryable”的“Select”方法填充对象的简单属性:
using (CustomerEntities context = new CustomerEntities())
{
IQueryable<SimpleCustomer> customers = context.Customers.Select(
c => new SimpleCustomer
{
Id = c.Id,
Name = c.Name
}
);
SimpleCustomer customer = customers.FirstOrDefault();
MessageBox.Show(customer.Name);
}
所以我的问题很简单:如何填充列表中的“电话”属性?
using (CustomerEntities context = new CustomerEntities())
{
IQueryable<SimpleCustomer> customers = context.Customers.Select(
c => new SimpleCustomer
{
Id = c.Id,
Name = c.Name
Phones = ///????
}
);
SimpleCustomer customer = customers.FirstOrDefault();
SimplePhone phone = customer.Phones.FirstOrDefault();
MessageBox.Show(customer.Name + " " + phone.Number);
}
如果我不清楚和/或您需要更多细节,请告诉我。
谢谢!
答案 0 :(得分:1)
我不确定您的问题是否还有其他问题,但据我了解,您只需致电ToList
,它就会被列为一个列表:
IQueryable<SimpleCustomer> customers =
context.Customers.Select(c => new SimpleCustomer
{
Id = c.Id,
Name = c.Name,
Phones = c.Phones.Select(p => new SimplePhone
{
Id = p.Id, // Unless you want the custom Id, i.e. c.Id
Number = p.Number
}).ToList();
});