Asp.net实体联接表选择对象列表

时间:2018-07-03 13:34:48

标签: asp.net entity-framework

是否有一种方法可以联接表以将结果选择到新对象的列表中?

这可行,但似乎开销更大

var results = (from Customers in db.Customers
               where Customers.id == id
               select new Customer{
                 PhoneNumbers = (from PhoneNumbers in db.PhoneNumbers
                                 where PhoneNumbers.CustomerId == Customers.id 
                                 select new PhoneNumber{
                                     phoneNumber = PhoneNumbers.phoneNumber
                                 }).ToList()
               }).FirstOrDefault();

AND

var results = (from Customers in db.Customers
               select new Customer{
                PhoneNumbers = (from PhoneNumbers in db.PhoneNumbers 
                                where PhoneNumbers.CustomerId == Customers.id
                                select new PhoneNumber{
                                    phoneNumber = PhoneNumbers.phoneNumber
                                 }).ToList()
                 }).ToList();

是否可以通过在开始搜索中包含表来减少开销?这样做(实际上是行不通的)

var results = (from Customers in db.Customers
             join PhoneNumbers in db.PhoneNumbers on Customers.id equals PhoneNumbers.CustomerId into grp1
              from PhoneNumbers in grp1.DefaultIfEmpty()
              select new Customer{
                PhoneNumbers = 'some select from grp or PhoneNumbers as a list'
               }).ToList();

0 个答案:

没有答案