简体   繁体   English

使用Entity Framework联接表的更好方法

[英]Better way to join tables with Entity Framework

Good morning, 早上好,

I have inherited a database with no foreign key relations and the project is such that i have to ignore this major issue and work around it. 我继承了一个没有外键关系的数据库,而该项目使我不得不忽略这个主要问题并加以解决。 Obviously this eliminates some of the cooler features of Entity Framework providing me related entities automatically. 显然,这消除了Entity Framework的一些凉爽功能,自动为我提供了相关的实体。

So i have been forced to do something like this: 所以我被迫做这样的事情:

using (var db = new MyEntities())
{
    Entities.Info record = db.Infoes.Where(x => x.UserId == authInfo.User.Id).FirstOrDefault();

    //Get all the accounts for the user
    List<Entities.AcctSummary> accounts = db.AcctSummaries.Where(x => x.InfoId == record.Id).ToList();

    //Loop through each account
    foreach (Entities.AcctSummary account in accounts)
    {
        //pull records for account
        List<Entities.Records> records= db.Records.Where(x => x.AcctSummaryId == account.Id).ToList();
    }
}

If there a better way to join the "record" and "accounts" Entities, or perhaps a more efficient way for getting "records" in a single query? 是否有更好的方式联接“记录”和“帐户”实体,或者是更有效的方式来在单个查询中获取“记录”?

TIA TIA

Are you just looking for the .Join() extension method? 您只是在寻找.Join()扩展方法吗? As an example, joining Infoes and Accounts might look like this: 例如,加入InfoesAccounts可能看起来像这样:

var accounts = db.Infoes.Join(db.Accounts,
                              i => i.Id,
                              a => a.InfoId,
                              (info, account) => new { info, account });

This would result in accounts being an enumeration of an anonymous type with two properties, one being the Info record and the other being the Account record. 这将导致accounts是具有两个属性的匿名类型的枚举,一个属性是Info记录,另一个属性是Account记录。 The collection would be the full superset of the joined records. 该集合将是联接记录的完整超集。

You can of course return something other than new { info, account } , it works just like anything you'd put into a .Select() clause. 当然,您可以返回除new { info, account } ,它的工作方式与您放入.Select()子句中的任何内容一样。 Whatever you select from these joined tables would be what you have an enumeration of in accounts . 从这些联接表中选择的任何内容都将是您在accounts的枚举。 You can further join more tables by changing .Join() extensions, returning whatever you want from each. 您可以通过更改.Join()扩展名来进一步.Join()更多表,并从每个表中返回所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM