如何使用CodeFirst填充不直接存储在数据库中的属性 [英] How to populate a property that is not directly stored in Database with CodeFirst
问题描述
SumTotal不应该保留在数据库中,而是每次检索Entity_A的实例时计算。
我查看了ComputedColumns,但似乎计算列只能相对于同一列中的列进行定义
我也有一种感觉,我需要将SumTotal设置为NotMapped(或与AutoGenerated类似的东西),但不知道如何将实际值设置为SumTotal。
希望这个问题有道理,谢谢提前
你可以将结果投影到匿名对象并将其转换为您的实体
var projection = db.EntityAs.Where(/ * * /)
.Select(a => new {A = a,Sum = a.Bs.Sum(b => b.Total)})
foreach(p in投影)
{
p .A.SumTotal = p.Sum;
}
var As = projection.Select(p => p.A);
I have 2 Entities, each of which is managed by EF Code First, and each happily sitting in its own table. Entity_A has a property, called "SumTotal", which should be the sum of a specific column in Entity_B that matches a certain criteria.
SumTotal should not be persisted in the DB, but rather calculated each time an instance of Entity_A is retrieved.
I have looked at ComputedColumns, but it appears that the computedcolumn can only be defined relative to columns in the same table.
I also have a feeling that I need to set SumTotal to NotMapped (or something similar with AutoGenerated), but dont know how to get the actual value into SumTotal.
Hope this question makes sense, thanks in advance
You can project the results to an anonymous object and transform that it to your entity
var projection = db.EntityAs.Where(/* */)
.Select(a => new {A = a, Sum = a.Bs.Sum(b => b.Total)})
foreach(p in projection)
{
p.A.SumTotal = p.Sum;
}
var As = projection.Select(p => p.A);
这篇关于如何使用CodeFirst填充不直接存储在数据库中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!