2017-08-17 87 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