2013-12-10 59 views
2

是否可以向EntityFramework CodeFirst屬性的getter/setter添加邏輯?是否可以重寫EF 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屬性可以返回前處理一點點。

回答

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; 
     { 
} 
+1

我不知道EF CodeFirst現在可以映射私有屬性:酷! – Seth

+0

在嘗試之前查找EF映射私有屬性。它看起來像你可以很容易地做到這一點與Linq實體 https://msdn.microsoft.com/en-us/library/system.data.linq.mapping.dataattribute.storage(v=vs.110).aspx #Anchor_2 但是如果你使用System.ComponentModel.DataAnnotations,你需要添加一堆代碼來支持它。 –

相關問題