实体框架 - 填充属性后运行函数

时间:2014-01-05 08:22:09

标签: c# asp.net-mvc entity-framework properties lazy-loading

在Entity Framework加载实体后,有没有办法填充属性?

例如 - 我有一个对象有一些非映射属性,我需要在Entity Framework加载所有其他属性后填充这些属性。我试图将逻辑填充到构造函数中,但它在填充任何其他属性之前运行,因此它们都读作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;
       }
    }
}

为了避免导航属性未及时加载的问题,我尝试通过将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;
      }
    }
}

1 个答案:

答案 0 :(得分:1)

没有可以执行代码的onload事件。

但是你可以让GatherRate成为一个功能。 (如果私有变量设置为null,则可能检查仅计算速率

[NotMapped]
private int? _GaterRate;

public int GaterRate() {
    if (!_GaterRate.HasValue)
        GaterRate = GetAllResourceGatherers();//this would have to return the GatherRate of course;

    return _GaterRate.Value;
 }

你甚至可以在一个特殊的get函数中以GaterRate为空时计算它(在第一次调用1时称为)