joh*_*kes 4 c# asp.net-mvc linq-to-sql
我有一个名为EntityRating的ViewModel,其中一个属性是AverageRating.
当我实例化我的ViewModel(称为EntityRating)类型的新对象时,如何根据相关项目的Rating字段(在SQL Server中)设置EntityRating.AverageRating?
我想做这样的事情(显然不起作用):
var er = new EntityRating()
{
AverageRating = _db.All<Ratings>(X => X.RatingID = rating.RatingID).Average(RatingField);
};
Run Code Online (Sandbox Code Playgroud)
我可以平均数据库中对象的属性并将其分配给代码中对象的属性吗?
(很新,所以如果有任何术语关闭,或者如果您需要更多信息,请告诉我)
谢谢.
.Average但是,LINQ具有扩展方法,仅适用于整数.所以你需要做的是获取数据库中所有对象IEnumerable的RatingField属性Rating.这可以通过使用.SelectLINQ 的扩展方法来实现Projects each element of a sequence into a new form.
int average = _db.Ratings
.Where(x => x.RatingID == rating.RatingID)
.Select(x => x.RatingField)
.Average();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4310 次 |
| 最近记录: |