2014-10-04 26 views
0

我在程序員中發佈了一段我的數據模型,詢問我的代碼的缺點是什麼,並得到了一些答案,肯定有潛在的問題。爲代碼第一個實體框架中的字段設計模型,對於某些緩存實體爲空?

https://softwareengineering.stackexchange.com/questions/258038/inheritance-is-a-null-property-in-the-parent-a-bad-practice

不好的做法是Amount場。它返回Null給一些實體,結論是我應該從父類中移除Amount字段,並在我需要它的類中使用它。

它現在使用代碼的方式是先使用數據表下面的模型以我想要的方式出現。該行字段的樣子:

Id, Title, Description, Amount, other fields 

每個實體種子的Amount場零或Null,視寧與否實體實際使用領域,一個類使用領域的指標是類必須覆蓋Amount

,當我刪除了Navigation類虛擬Amount,只是放置在類的Amount場被我實際存儲量會發生什麼,在數據庫中的表看起來像這樣:

Id, Title, Description, Amount, Amount1, Amount2, other fields 

這由於許多原因是不希望的結果。

問題是我該怎麼做,所以我只有一個Amount字段在數據表中?

public class Navigation 
{ 
    int Id { get; set; } 
    string Title { get; set; } 
    string Description { get; set; } 
    ObservableCollection<Navigation> Children { get; set; } 

    public virtual decimal? Amount 
    { 
     get { return null; } 
     set { value = null; } 
    } 
} 

public class C1 : Navigation { } 

public class C2 : Navigation { } 

public class C3 : Navigation 
{ 
    private decimal _amount; 

    public override decimal? Amount 
    { 
     get { return _amount; } 
     set { if (value != null) _amount = (decimal)value; } 
    } 
} 

public class C4 : Navigation 
{ 
    private decimal _amount; 

    public override decimal? Amount 
    { 
     get { return _amount; } 
     set { if (value != null) _amount = (decimal)value; } 
    } 
} 

回答

0

試試這個,不知道它是否會工作。你使用什麼版本的EF?

protected override void OnModelCreating(ModelBuilder modelBuilder) 
{ 
    modelBuilder.Entity<C3>().Property(p => p.Amount).HasColumnName("Amount"); 
    modelBuilder.Entity<C4>().Property(p => p.Amount).HasColumnName("Amount"); 
} 
+0

6. + EF。是的,我在考慮是否有解決方案。我會給它一個鏡頭。 – Jon 2014-10-04 09:20:24

+0

@Jon讓我知道它是怎麼回事。 – artm 2014-10-04 10:42:13

+0

今天早上我用一種解決方案醒來了,我想我會嘗試一下,然後才用流利的api來試用它。 – Jon 2014-10-04 19:25:45

0

解決方法是改變繼承。我從導航中刪除了金額字段。在C3虛擬中創建金額字段,並將C4更改爲從C3繼承。工作正常。

public class Navigation 
{ 
    int Id { get; set; } 
    string Title { get; set; } 
    string Description { get; set; } 
    ObservableCollection<Navigation> Children { get; set; } 

// public virtual decimal? Amount 
// { 
//  get { return null; } 
//  set { value = null; } 
// } 
} 

public class C1 : Navigation { } 

public class C2 : Navigation { } 

public class C3 : Navigation 
{ 
    private decimal _amount; 

    public virtual decimal? Amount 
    { 
     get { return _amount; } 
     set { if (value != null) _amount = (decimal)value; } 
    } 
} 

public class C4 : C3 
{ 
    private decimal _amount; 

    public override decimal? Amount 
    { 
     get { return _amount; } 
     set { if (value != null) _amount = (decimal)value; } 
    } 
} 
相關問題