如何使用CodeFirst填充不直接存储在数据库中的属性 [英] How to populate a property that is not directly stored in Database with CodeFirst

查看:161
本文介绍了如何使用CodeFirst填充不直接存储在数据库中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实体,每个实体由EF Code First管理,每个都高兴地坐在自己的表中。 Entity_A有一个名为SumTotal的属性,它应该是Entity_B中与特定条件匹配的特定列的总和。



SumTotal不应该保留在数据库中,而是每次检索Entity_A的实例时计算。



我查看了ComputedColumns,但似乎计算列只能相对于同一列中的列进行定义



我也有一种感觉,我需要将SumTotal设置为NotMapped(或与AutoGenerated类似的东西),但不知道如何将实际值设置为SumTotal。



希望这个问题有道理,谢谢提前

解决方案

你可以将结果投影到匿名对象并将其转换为您的实体

  var projection = db.EntityAs.Where(/ * * /)
.Select(a => new {A = a,Sum = a.Bs.Sum(b => b.T​​otal)})

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆