gpt4 book ai didi

c# - Fluent API EF 继承和映射

转载 作者:太空狗 更新时间:2023-10-29 21:44:35 27 4
gpt4 key购买 nike

我有一个系统,其中包含多个具有一对多关系(父子关系)的自引用实体。我想为所有这些实体使用公共(public)基类:

public class SelfReferencing
{
public SelfReferencing Parent {get; set;}
public ICollection<SelfReferencing> Children {get; set;}
}

并从 SelfReferencing 继承特定的实体。在尝试执行以下操作时,Fluent API 映射要求引用属性为定义类型:

modelBuilder.Entity<ConcreteSelfReferencing>()
.HasMany(e => e.Children)
.WithOptional(e => e.Parent);

那么,你能帮我找到一种利用继承并映射实体的可能性吗?

谢谢

最佳答案

Note: The example below is known as Table-Per-Hierarchy (TPH) - i.e. all contained in one table. Click on this link for Table-Per-Type (TPT), which has different tables for each type.

当使用基类型和继承类型时,您必须告诉 EF 如何确定特定继承类型的关联。

获取您的代码:

public abstract class SelfReferencing
{
public SelfReferencing Parent { get; set; }
public ICollection<SelfReferencing> Children { get; set; }
}

public class ConcreteSelfReferencing : SelfReferencing
{
}

EF 现在必须确定子类是 ConcreteSelfReferencing 还是任何其他类型的子类。这是由表本身的鉴别器确定的,到该表的列不是映射的一部分。

再举个例子,类似于我过去用过的:

public abstract class Policy
{
public int Id { get; set; }
public string PolicyNumber { get; set; }
}

public class InsurancePolicy : Policy
{
}

public class CarPolicy : Policy
{
}

表格的结构是这样的:

| Id    |   PolicyNumber  | Type  |  ..... |
1 CAR0001 C
2 ISN0001 I

要让 EF 正确生成它们,您需要:

public class MyContext : DbContext
{
public MyContext() : base()
{
}

public DbSet<Policy> Policies { get; set; }

protected override void OnModelCreating(ModelBuilder builder)
{
var policyMap = modelBuilder.Entity<Policy>();

// Set up discriminators
policyMap.Map<InsurancePolicy>(p => o.Requires("Type").HasValue("I"))
.Map<CarPolicy>(p => o.Requires("Type").HasValue("C"));

// Notice that `Type` is only used for the discriminators, not an actual
// mapped property
policyMap.HasKey(x=>x.Id);
policyMap.Property(x=>x.PolicyNumber);
}
}

从您的代码中,您可以自己进行过滤,或者将过滤放在 DbContext 中。这是来自单独类(class)的示例。

public class PolicyRepository
{
private MyContext context = new MyContext();

public PolicyRepository()
{
}

public IQueryable<InsurancePolicy> GetInsurancePolicies()
{
return this.context.Policies.OfType<InsurancePolicy>();
}

public IQueryable<CarPolicy> GetCarPolicies()
{
return this.context.Policies.OfType<CarPolicy>();
}
}

关于c# - Fluent API EF 继承和映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23997972/

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