Cross Join in Entity framework Lambda Expressions

半城伤御伤魂 提交于 2021-02-15 06:58:02

问题


How can I do the following join in EF? Tables have no relation with each other, no foreign keys.

Select t1.ID,  t1.firstname, t2.ID,t2.name from MY_TEST_TABLE1 t1, MY_TEST_TABLE2 t2
where t1.firstname = t2.name

回答1:


You could do this:

var query= from t1 in context.MY_TEST_TABLE1
           from t2 in context.MY_TEST_TABLE2
           where t1.firstname == t2.name
           select new { Table1Id= t1.ID, FirstName= t1.firstname, Table2Id=t2.ID,Name= t2.name};

Another way to do a cross join in Linq to Entities is using SelectMany extension method:

var query= context.MY_TEST_TABLE1.SelectMany(
    t1=>context.MY_TEST_TABLE2
        .Where(t2=>t1.firstname == t2.name)
        .Select(t2=>new { 
            Table1Id= t1.ID,
            FirstName= t1.firstname, 
            Table2Id=t2.ID,
            Name= t2.name
        })
    );



回答2:


Maybe something like this:

var results = from t1 in dbcontext.my_test_table1s
              join t2 in dbcontext.my_test_table2s on t1.firstname equals t2.name
              select new 
              { 
                   t1id = t1.Id, 
                   firstname = t1.firstname, 
                   t2id = t2.id, 
                   name = t2.name 
              };


来源:https://stackoverflow.com/questions/35375150/cross-join-in-entity-framework-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!