投影查詢

如果需要非規範化型別中的相關資料,或者例如僅需要列的子集,則可以使用投影查詢。如果沒有理由使用額外型別,則可以將值加入匿名型別

var dbContext = new MyDbContext();
var denormalizedType = from company in dbContext.Company
                       where company.Name == "MyFavoriteCompany"
                       join founder in dbContext.Founder
                       on company.FounderId equals founder.Id
                       select new 
                       {
                           CompanyName = company.Name,
                           CompanyId = company.Id,
                           FounderName = founder.Name,
                           FounderId = founder.Id
                       };

或者使用查詢語法:

var dbContext = new MyDbContext();
var denormalizedType = dbContext.Company
                       .Join(dbContext.Founder, 
                                    c => c.FounderId,
                                    f => f.Id ,
                                    (c, f) => new 
                                    {
                                        CompanyName = c.Name,
                                        CompanyId = c.Id,
                                        FounderName = f.Name,
                                        FounderId = f.Id
                                    })
                       .Select(cf => cf);