EF Core中的零或一关系 [英] Zero-or-one relationship in EF Core

查看:79
本文介绍了EF Core中的零或一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在EF Core中有一个零或一关系的特殊情况,默认情况下不容易建模(例如,如

I have a somewhat special scenario of a Zero-or-one relationship in EF Core which cannot be easily modeled by the default (as described, e.g.,in EF Core One to One or Zero Relationship).

我有多个与匹配"对象具有0-1关系的实体,实体.多个实例可以引用相同的"Match".实体(这就是为什么我不能将外键放入匹配"表中的原因,这似乎是对0-1关系建模的推荐方式.)

I've got multiple entities with a 0-1 relationship to a "Match" entity. Multiple instances can reference the same "Match" entity (which is why I can't put the foreign key into the "Match" table, which seems to be the recommended way of modeling a 0-1 relationship).

如何定义从实体之一到0-1匹配"的关系?实体?我是否必须创建Match().HasMany(someKindOfBaseClassOfEntities)?有更好的方法吗?

How to define the relationship from one of the entities to 0-1 "Match" entities? Do I have to create a Match().HasMany(someKindOfBaseClassOfEntities) instead? Is there a better way?

推荐答案

您可以使用 HasOne (允许1:0..1的关系)进行配置.仅显示一种执行此操作的方法,而无需重复太多映射代码:

You can configure this by using HasOne, which allows a 1:0..1 relationship. Just showing one way of doing this without repeating too much mapping code:

课程:

class Match
{
    public int ID { get; set; }
    public string Name { get; set; }
}

abstract class HasMatchBase
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int? MatchID { get; set; }
    public Match Match { get; set; }
}

class A : HasMatchBase
{
    public string Code { get; set; } // Just an example
}

class B : HasMatchBase { }

映射配置:

abstract class HasMatchBaseConfig<T> : IEntityTypeConfiguration<T>
    where T : HasMatchBase
{
    public void Configure(EntityTypeBuilder<T> builder)
    {
        builder.Property(b => b.Name).HasMaxLength(200);
        builder.HasOne(b => b.Match).WithOne().HasForeignKey<T>(b => b.MatchID);

        ConfigureMatchOwner(builder);
    }
    
    public abstract void ConfigureMatchOwner(EntityTypeBuilder<T> builder);
}

class AConfig : HasMatchBaseConfig<A> 
{ 
    public override void ConfigureMatchOwner(EntityTypeBuilder<A> builder)
    {
        builder.Property(a => a.Code).HasColumnType("CHAR").HasMaxLength(3);
        ... // Further A-specific mapping
    }
}

class BConfig : HasMatchBaseConfig<B>
{
    public override void ConfigureMatchOwner(EntityTypeBuilder<B> builder)
    {
        ... // B-specific mapping. 
    }
}

HasMatchBase.MatchID 的类型确定关联是必需的还是可选的.在这种情况下,它是一个可为空的 int ,将关联转换为 Match 是可选的.

The type of HasMatchBase.MatchID determines whether the association is required or optional. In this case it's a nullable int, turning the association into Match being optional.

这篇关于EF Core中的零或一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆