gpt4 book ai didi

c# - Entity Framework 6 : ignore property on basetype for all derived types

转载 作者:行者123 更新时间:2023-12-05 02:18:19 40 4
gpt4 key购买 nike

我需要忽略 abstract class BaseEntity 上的属性 State,但如果不使用 [NotMappedAttribute],我无法让它工作>,但如果我使用属性,该属性也会在 OData API 中被忽略。

我已经建立了一个 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.

我需要让它与 Fluent api 一起工作,我需要同时对 BaseEntity 的所有派生类型执行此操作。

在我的真实项目中,我有 100 多个实体,我无法为每个实体手动执行此操作,尤其是考虑到 future 的发展。

最佳答案

该问题似乎与以下事实有关:Types 方法体会为每个直接或间接继承 BaseEntity 的类调用,这会导致 EF 继承出现问题。

您可以做的是使用过滤器仅对直接派生类型应用配置,如下所示:

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

关于c# - Entity Framework 6 : ignore property on basetype for all derived types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45730674/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com