[英]How to update all rows of a table with an aggregate value referenced by foreign key on an another table in Entity Framework
I have a users table and my User
entity has a Rating
column. 我有一个用户表,我的User
实体有一个Rating
列。 A User
has a navigation property called IncomingRatings
, which is a one-to-many relationship of list of Rate
s from a table called rates. User
具有一个称为IncomingRatings
的导航属性,该属性是来自名为rate的表中Rate
列表的一对多关系。 A rating can be positive or negative, and is represented by the IsPositive
boolean. 评分可以是正数或负数,并由IsPositive
布尔值表示。
I want to find all the ratings of that user, and store it in the Rating
column of my User
table. 我想找到该用户的所有评分,并将其存储在“ User
表的“ Rating
列中。 Consider the following sample data: 考虑以下样本数据:
RaterID | RatedID | IsPositive
1 2 1
4 1 0
5 2 1
2 3 0
3 2 1
7 2 0
6 1 1
In this case, for example, I want my user #2's (referenced by ID 2) Rating
field to become 3, as there are 3 positive ratings for her. 例如,在这种情况下,我希望我的用户#2的(由ID 2引用)“ Rating
字段变为3,因为她的评分为3。
After the updates, the users table should be like this: 更新之后,用户表应如下所示:
UserID | Rating
1 1
2 3
3 0
4 0
5 0
6 0
7 0
Because I need this statement to run for 10000+ records, I can't use regular for loop in my ASP.NET website to update the records as it will save them one-by-one when I call SaveChanges
. 因为我需要该语句来运行10000条以上的记录,所以我无法在ASP.NET网站中使用常规的for循环来更新记录,因为当我调用SaveChanges
时,它将逐一保存它们。 I've found EntityFramework.Extended which can update many records in a single call. 我发现EntityFramework.Extended可以在一个调用中更新许多记录。 Here is my two approaches: 这是我的两种方法:
db.Users.Where(u => true).Update(u => new User { Rating = u.IncomingRatings.Count(r => r.IsPositive) });
db.Users.Where(u => true).Update(u => new User { Rating = db.Rates.Where(r => r.RatedID == u.ID && r.IsPositive).Count() });
However, I am getting An aggregate may not appear in the set list of an UPDATE statement.
但是,我得到An aggregate may not appear in the set list of an UPDATE statement.
error in both queries. 两个查询中均出现错误。 How can I update all rows with an aggregate value in Entity Framework 6.1? 如何在Entity Framework 6.1中使用汇总值更新所有行?
Looks like EntityFramework.Extended
is only capable of building simple UPDATE statement like 看起来像EntityFramework.Extended
仅能构建简单的UPDATE语句,例如
UPDATE User SET Rating = 3 WHERE ...
and not (or not yet) 而不是(或尚未)
UPDATE User SET Rating = (SELECT Count(*) FROM ... )
Too bad... 太糟糕了...
If doing the updates by regular EF updates, but with one SaveChanges()
call, is too slow you could consider executing raw SQL to do the job. 如果通过常规的EF更新进行更新,但是只调用一次SaveChanges()
,则速度太慢,您可以考虑执行原始SQL来完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.