简体   繁体   English

如何使用Linq为SelectMany聚合两个以上的实体?

[英]How to aggregate more than two entities using Linq for a SelectMany?

I have a database with multiple tables that I am trying to "flatten" into one table on another database. 我有一个包含多个表的数据库,我试图将这些表“展平”到另一个数据库的一个表中。 I am able to easily do this with Entity Framework using only two tables (or entities), but trying to add in 3 or more gives me compile errors. 我可以仅使用两个表(或实体)使用Entity Framework轻松完成此操作,但是尝试添加3个或更多表会出现编译错误。 There's got to be a way to do this, right? 必须有一种方法可以做到,对吗? I feel like I am not formatting my expression correctly. 我觉得我的格式表达不正确。 Please look at how I have it set up with two entities below: 请查看下面的两个实体如何设置它:

var flatTable= DB1.MainTable.SelectMany(mt => DB1.SecondaryTable.Where(st => st.MainID == mt.MainID),  (mt, st) => new FlatTable
{
    MainID = mt.MainID,
    AgeLessThan1 = st.AgeLessThan1,
    Age1to4 = st.Age1to4,
    Age5to19 = st.Age5to19,
    Age20to49 = st.Age20to49,
    AgeGreaterThanEqual50 = st.AgeGreaterThanEqual50,
    AgeUnknown = st.AgeUnknown
}).ToList();

The above code successfully gets data from the two tables on the first database and creates new aggregate rows to be inserted into the "flat" table on the other database. 上面的代码成功地从第一个数据库的两个表中获取了数据,并创建了新的聚合行以插入到另一个数据库的“ flat”表中。 My issue is that this entity, FlatTable that is being created has many more fields that need to be populated from other tables that I can't seem to add within this chunk of code. 我的问题是,正在创建的这个实体FlatTable具有许多其他字段,这些字段需要从我似乎无法在此代码块中添加的其他表中填充。 Is what I am asking possible, or will I have to add in the fields from each additional table in multiple steps? 我想问的是可能的吗,还是我必须分多个步骤在每个其他表中添加字段?

Below is the code for adding the finished aggregate data to the new table on the second database: 下面是将完成的汇总数据添加到第二个数据库的新表中的代码:

foreach (flatRow row in flatTable)
{
    T2.AddToFlatTable(row);
}
T2.SaveChanges();

Without seeing any other code or your database structure, you should be able to achieve the same thing using joins instead of SelectMany . 在没有看到任何其他代码或数据库结构的情况下,您应该能够使用联接而不是SelectMany来实现相同的目的。

from mainrow in DB1.MainTable
    join secondrow in DB1.SecondaryTable on mainrow.MainID equals secondrow.MainID
    join thirdrow in DB2.ThirdTable on mainrow.MainID equals thirdrow.MainID
select new FlatTable
{
    MainID = mainrow.MainID,
    AgeLessThan1 = secondrow.AgeLessThan1,
    Age1to4 = secondrow.Age1to4,
    Age5to19 = secondrow.Age5to19,
    Age20to49 = secondrow.Age20to49,
    AgeGreaterThanEqual50 = secondrow.AgeGreaterThanEqual50,
    AgeUnknown = secondrow.AgeUnknown,
    ThirdTableField = thirdrow.Field
    //etc
}

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

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