2017-08-17 65 views
1

我需要忽略abstract class BaseEntity上的State屬性,但我不能在不使用[NotMappedAttribute]的情況下工作,但如果使用該屬性,屬性也會被忽略在OData API中。實體框架6:忽略所有派生類型的基類型的屬性

我已成立了一個GitHub的項目在這裏測試: https://github.com/nurf3d/EntityFrameworkDerivedTypesIgnoreProperiesTest/tree/master

繼承鏈:

public abstract class BaseEntity 
{ 
    [Key] 
    public int ID { get; set; } 

    [Timestamp] 
    public byte[] Rowversion { get; set; } 

    public State State { get; set; } 
} 

[Table("Events")] 
public abstract class Event : BaseEntity 
{ 
    public int PersonID { get; set; } 

    public string EventName { get; set; } 

    public virtual Person Person { get; set; } 
} 

public class DerivedEvent1 : Event 
{ 
    public bool IsDerivedEvent1 { get; set; } 
} 

public class DerivedEvent2 : Event 
{ 
    public bool IsDerivedEvent2 { get; set; } 
} 

屬性

當使用[NotMappedAttribute],在State屬性格式獲取忽略所有類型都正確並且遷移運行良好,但是這也會從OData API中刪除屬性,這是我們不想要的。

由於我們需要OData API內的State屬性,因此我們不使用[NotMappedAttribute],而是使用流暢的配置。

流利的配置:

modelBuilder.Types<BaseEntity>().Configure(clazz => clazz.Ignore(prop => prop.State)); 

add-migration Initial -Force 

導致此錯誤:

You cannot use Ignore method on the property 'State' on type 'EntityFrameworkIgnoreProperty.Models.DerivedEvent1' because this type inherits from the type 'EntityFrameworkIgnoreProperty.Models.BaseEntity' where this property is mapped. To exclude this property from your model, use NotMappedAttribute or Ignore method on the base type.

我需要得到這個與流暢API的工作,我需要在所有派生類型的BaseEntity做到這一點一旦。

在我的真實項目中,我有100多個實體,我無法親自爲每一個實體做這件事,特別是考慮到未來的發展。

+0

被映射爲實體(即參加EF繼承)'BaseEntity'類? –

+0

否'BaseEntity'沒有被映射爲單獨的實體。在這個例子中,只有Event應該被映射爲一個具有TPH的實體。 – Nurfed

回答

2

該問題似乎與以下事實有關:Types方法體被直接或間接地調用,繼承BaseEntity的每個類都會導致EF繼承問題。

你可以做的是使用過濾器,應用此配置只對直接派生類型是這樣的:

modelBuilder.Types<BaseEntity>() 
    .Where(t => t.BaseType == typeof(BaseEntity)) 
    .Configure(clazz => clazz.Ignore(prop => prop.State)); 
+0

謝謝你做到了!我知道我以前已經有過,但我不記得我用過它的問題..無論如何...這似乎解決了我所有的問題! – Nurfed

相關問題