简体   繁体   中英

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. 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. 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. 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 .

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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