是否可以覆盖EF CodeFirst属性的getter / setter?

时间:2013-12-10 22:40:21

标签: entity-framework ef-code-first

是否可以为EntityFramework CodeFirst属性的getter / setter添加逻辑?

例如,我想做类似的事情:

public class Dog {
     // This is a normal EF-backed property....
     public virtual string Breed { get; set; }

     // But we'd like a little logic applied to the Name!
     public virtual string Name {
          get {
               string nameInDB = base.Name; 
               // where base.Name would be the same as the naked "get;" accessor

               if (nameInDB == "Fido") {
                   return "Fido the Third"
               } else {
                   return nameInDB;
               }
          }
          set;
     }
}

public class PetContext : DbContext {
    public DbSet<Dog> Dogs;
}

返回之前可以稍微处理Dog.Name属性。

1 个答案:

答案 0 :(得分:4)

您可以使用支持字段,而不是依赖于自动实现的属性。

private string _Name;
public string Name {
      get {
           if (_Name == "Fido") {
               return "Fido the Third";
           } else {
               return _Name;
           }
      }
      set {
           _Name = value;
      {
 }

但是,通过控制setter中的值,我会采取相反的方式。对我而言,即使在调试方案中,这也为模型提供了更多的一致性。你需要考虑你的实际规格,看看哪种更适合你。例如:

private string _Name;
public string Name {
      get {
           return _Name;
      }
      set {
           if (value == "Fido")
               _Name = "Fido the Third";
           _Name = value;
      {
 }
相关问题