本文介绍了实体框架与LINQ聚合连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说很容易在TSQL中执行,但我只是坐在这里,把我的头撞到桌面,试图让它在EF4中工作!



我有一张桌子,让它叫做TestData。它有字段,例如:DataTypeID,Name,DataValue。

  DataTypeID,Name,DataValue 
1,Data 1 ,Value1
1,Data 1,Value2
2,Data 1,Value3
3,Data 1,Value4

我想对DataID / Name进行分组,并将DataValue连接成CSV字符串。所需的结果应包含 -

  DataTypeID,Name,DataValues 
1,Data 1,Value1,Value2
2,数据1,Value3
3,数据1,Value4

现在,我正在尝试这样做 -

  var query =(from t在context.TestData 
组h通过新的{DataTypeID = h.DataTypeID,Name = h.Name}到g
选择新
{
DataTypeID = g.Key.DataTypeID,
Name = g.Key.Name,
DataValues =(string)g.Aggregate(,(a,b)=>(a!=?,: + b.DataValue),
})ToList()

问题是LINQ到实体不知道如何将其转换为SQL。这是3个LINQ查询的联合的一部分,我真的很喜欢它这样保持。我想我可以检索数据,然后再执行聚合。出于性能原因,这对我的应用程序无效。我也考虑使用SQL服务器功能。但是,在EF4世界中,这似乎并不是正确的。



任何人都有意在此开裂?

解决方案

感谢moi_meme的答案。我希望做的是不可能与LINQ对实体。如其他人所建议的,您必须使用LINQ to Objects才能访问字符串操作方法。



查看moi_meme发布的链接以获取更多信息 -
(更新链接,感谢jnm2让我知道)


This is easy for me to perform in TSQL, but I'm just sitting here banging my head against the desk trying to get it to work in EF4!

I have a table, lets call it TestData. It has fields, say: DataTypeID, Name, DataValue.

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

I want to group on DataID/Name, and concatenate DataValue into a CSV string. The desired result should contain -

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

Now, here's how I'm trying to do it -

var query = (from t in context.TestData
  group h by new { DataTypeID = h.DataTypeID, Name = h.Name } into g
  select new
 {
   DataTypeID = g.Key.DataTypeID,
   Name = g.Key.Name,
   DataValues = (string)g.Aggregate("", (a, b) => (a != "" ? "," : "") + b.DataValue),
 }).ToList()

The problem is that LINQ to Entities does not know how to convert this into SQL. This is part of a union of 3 LINQ queries, and I'd really like it to keep it that way. I imagine that I could retrieve the data and then perform the aggregate later. For performance reasons, that wouldn't work for my app. I also considered using a SQL server function. But that just doesn't seem "right" in the EF4 world.

Anyone care to take a crack at this?

解决方案

Thanks to moi_meme for the answer. What I was hoping to do is NOT POSSIBLE with LINQ to Entities. As others have suggested, you have to use LINQ to Objects to get access to string manipulation methods.

See the link posted by moi_meme for more info -(Updated Link, thanks jnm2 for letting me know) http://www.purritos.com/blog/archives/4510

这篇关于实体框架与LINQ聚合连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:47