字符串,在实体框架中联接,LINQ to SQL,无客户端求值

ca1c2owp  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(157)

如果您有类似here的数据表:

DataTypeID, DataValue
1,"Value1"
1,"Value2"
2,"Value3"
3,"Value4"

并希望输出如下所示:

DataTypeID,DataValues
1,"Value1,Value2"
2,"Value3"
3,"Value4"

大多数问题建议像this一样使用toList()或AsEnumerable(),然后在客户端使用string.Join(“,“,DataValues)。如果数据不是很大,这可能会起作用,但它违背了使用EF的目的。我如何在不将所有数据加载到内存中的情况下完成此操作?

kqlmhetl

kqlmhetl1#

UPDATE:从EF7 preview 7开始,现在只需使用string.Joinnormally作为示例:

_context.MyTable
    .GroupBy(keySelector => keySelector.MyKey, elemSelector => elemSelector.StringProp)
    .Select(elem => string.Join(',', elem))
   //.FirstOrDefaultAsync(cancellationToken), if (keyselector => 1) i.e. only 1 group so you get all rows

"旧答案"
好吧,根据这个this issue,string.Join()还没有实现(到现在为止),IEnumerable.Aggregate也不会转换。

  • 同时 *,您可以创建一个视图并在其中编写SQL。例如,按id和string分组。Join(“,“,Names);
CREATE VIEW V_Name AS
SELECT ID,  
Names=STUFF  
(  
    (  
      SELECT DISTINCT ' || '+ CAST(Child.Name AS VARCHAR(MAX))  
      FROM Child,MainTable
      WHERE Main.ID= t1.ID --this line is imp...
      AND Child.ID=MainTable.ID
      FOR XMl PATH('')  
    ),1,1,''  
)  
FROM MainTable t1 
GROUP BY t1.IDReview

CREATE VIEW V_Name AS
SELECT ID, STRING_AGG(Name, ', ') AS Names
FROM MainTable
LEFT JOIN ChildTable ON MainTable.ID = ChildTable.ID
GROUP BY ID

现在,在C#中,您可以简单地将它与您的ID连接起来,就像您通常使用IQueryable一样:

from data in _dbcontext.sometable
       join groupedAndJoinedNames in _dbcontext.viewname
                on data.ID equals groupedAndJoinedNames.ID
       select new
       {
            Names = groupedAndJoinedNames.Names
       }

相关问题