更改 LINQ 语句中对象的值
我想向 EntityObject 添加一些计算属性,而又不失去再次查询数据库的可能性。
我创建了一个分部类并在对象中添加了我需要的字段。我编写了一个静态函数“AttachProperties”,它应该以某种方式添加一些计算值。我无法在客户端执行此操作,因为其他几个函数将一些过滤条件附加到查询中。
这些函数应该如下所示:
return query.Select(o =>
{
o.HasCalculatedProperties = true;
o.Value = 2;
return o;
});
在我的例子中,计算值取决于多次查找,而不仅仅是一个简单的“2”。该示例适用于 IEnumerable,但当然不适用于 IQueryable。
我首先创建了一个新类,其中 EntityObject 作为属性,并添加了其他必要的字段,但现在我需要这个扩展类具有相同的基类型。
I want to add some calculated properties to an EntityObject without loosing the possibility of querying it agains the database.
I created a partial class and added the fields I need in the object. Than I wrote a static function "AttachProperties" that should somehow add some calculated values. I cannot do this on clientside, since several other functions attach some filter-conditions to the query.
The functions should look like this:
return query.Select(o =>
{
o.HasCalculatedProperties = true;
o.Value = 2;
return o;
});
In my case the calculated value depends on several lookups and is not just a simple "2". This sample works with an IEnumerable but, of course, not with an IQueryable
I first created a new class with the EntityObject as property and added the other necessary fields but now I need this extended class to be of the same basetype.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,在我看来,改变 Select() 中的对象是一个坏主意,因为它会导致其他事情发生(状态改变),而不是方法名称所暗示的(投影),这总是会带来麻烦。 Linq 植根于函数式编程(无状态)范例,因此这种用法是不可预期的。
但是您可以使用返回计算结果的方法来扩展您的类,例如:
从您的问题中很难判断这是否适合您。如果生成计算值涉及的不仅仅是根据对象自身属性进行简单计算,那么最好不要理会实体并创建从对象图返回计算结果的服务。
First, in my opinion changing objects in a Select() is a bad idea, because it makes something else happen (state change) than the method name suggests (projection), which is always a recipe for trouble. Linq is rooted in a functional programming (stateless) paradigm, so this kind of usage is just not expected.
But you can extend your class with methods that return a calculation result, like:
It is a bit hard to tell from your question whether this will work for you. If generating a calculated value involves more than a simple calculation from an object's own properties it may be better to leave your entities alone and create a services that return calculation results from an object graph.
尝试这样的操作:
这将创建原始对象的副本,其中包含您所需的更改,并避免修改 select 子句中的实体带来的所有混乱。
Try something like this:
This will create a copy of the original object with the changes you require and avoid all the messiness that come with modifying an entity in a select clause.