Luk*_*keP 6 c# asp.net-mvc entity-framework lazy-loading properties
有没有办法在实体框架加载实体后填充属性?
例如 - 我有一个对象,它有几个非映射属性,我需要在实体框架加载所有其他属性后填充这些属性。我尝试将填充属性的逻辑放入构造函数中,但它在填充任何其他属性之前运行,因此它们都读取为null
.
public class Planet
{
public Planet()
{
//this does not work because the Structures
//and Ships properties return null
GetAllResourceGatherers();
}
public int Id { get; set; }
public ICollection<Structure> Structures { get; set; }
public ICollection<Ship> Ships { get; set; }
[NotMapped]
public int GatherRate {get; private set;}
public void GetAllResourceGatherers
{
var resourceGatherers = Ships.OfType<IResourceGatherer>().ToList();
resourceStorers.AddRange(Structures.OfType<IResourceStorer>().ToList());
foreach (var gatherer in resourceGatherers)
{
gatherRate += gatherer.GatherRate;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免导航属性未及时加载的问题,我尝试通过将方法更改GetAllResourceGatherers()
为:
public void GetAllResourceGatherers
{
using (var db = new DbContext())
{
//This does not work because the 'Id' property comes back.
//as 0 which is just default
Structures = db.Structures.Where(x => x.ParentId == Id).ToList();
Ships = db.Ships.Where(x => x.ParentId == Id).ToList();
var resourceGatherers = Ships.OfType<IResourceGatherer>().ToList();
resourceStorers.AddRange(Structures.OfType<IResourceStorer>().ToList());
foreach (var gatherer in resourceGatherers)
{
gatherRate += gatherer.GatherRate;
}
}
}
Run Code Online (Sandbox Code Playgroud)
没有可以执行代码的 onload 事件。
但是您可以将 GatherRate 设为一个函数。(如果私有变量设置为空,则可能进行检查以仅计算速率
[NotMapped]
private int? _GaterRate;
public int GaterRate() {
if (!_GaterRate.HasValue)
GaterRate = GetAllResourceGatherers();//this would have to return the GatherRate of course;
return _GaterRate.Value;
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以在一个特殊的 get 函数中以这种方式在 GaterRate 为 null 时进行计算(假设第一次调用 1)
归档时间: |
|
查看次数: |
2440 次 |
最近记录: |