首页 > 解决方案 > EF Core ForeignKey-like 关系

问题描述

考虑两个类:

public class EntA
{
    public Guid Id { get; set; }
    [ForeignKey("EntityId")]
    public ICollection<TranslationValue> Translations { get; set; }
}
public class EntB
{
    public Guid Id { get; set; }
    [ForeignKey("EntityId")]
    public ICollection<TranslationValue> Translations { get; set; }
}

然后我们有 TranslationValue 类:

public class TranslationValue : IEntity
{
    public Guid Id { get; set; }
    public Guid EntityId { get; set; }
    public string Value { get; set; }
}

这一切都很好,除了一件事:我不能有外键作为 TranslationValue.EntityId 中的条目将同时引用 EntA 和 EntB。

所以问题是:如何在不实际创建外键的情况下以与上述完全相同的方式定义关系。

我目前使用的解决方法是创建迁移,然后删除负责创建实际外键的部分。

标签: .netentity-framework

解决方案


所以问题是:如何在不实际创建外键的情况下以与上述完全相同的方式定义关系。

这是不可能的,因为单个外键将如何映射到两个不同的表?您的TranslationValue模型必须如下:

public class TranslationValue : IEntity
{
    public Guid Id { get; set; }

    public Guid EntAId { get; set; }
    public Guid EntBId { get; set; }

    public string Value { get; set; }

    public EntA EntA {get; set;}
    public EntB EntB {get; set;}
}

推荐阅读