简体   繁体   English

EF Core 3:反向外键关系

[英]EF Core 3: reverse foreign key relation

Consider these model relations:考虑这些 model 关系:

public class A
{
    [Key]
    public int Id { get; set; }
    public int BId { get; set; }
    public ICollection<B> Bs { get; set; }
}

public class D
{
    [Key]
    public int Id { get; set; }
    public int BId { get; set; }
    public ICollection<B> Bs { get; set; }
}

public class B
{
    public int Id { get; set; }
    public int CId { get; set; }
    public C C { get; set; }
}

public class C
{
    [Key]
    public int Id { get; set; }
}

With this configuration:使用此配置:

modelBuilder.Entity<B>()
    .HasKey(x => new { x.Id, x.CId });

modelBuilder.Entity<A>()
    .HasMany(a => a.Bs)
    .WithOne()
    .HasForeignKey(b => b.Id)
    .HasPrincipalKey(a => a.Id);

modelBuilder.Entity<D>()
    .HasMany(a => a.Bs)
    .WithOne()
    .HasForeignKey(b => b.Id)
    .HasPrincipalKey(a => a.Id);

The intent was to reuse B 's among A and D however EF Core creates foreign-key constraints on the table for B meaning that I can't have entries that are associated with A without being associated with B also.目的是在AD之间重用B ,但是 EF Core 在B的表上创建外键约束,这意味着我不能拥有与A关联但不与B关联的条目。

Is there a way to define the constraints so that it exists on A and D instead?有没有办法定义约束,使其存在于AD上?

This is a database modeling question (not EF core) and we would need more real life information to really help.这是一个数据库建模问题(不是 EF 核心),我们需要更多现实生活中的信息才能真正提供帮助。

Be that as it may, the foreign key is properly placed from your code on A and D .尽管如此,外键已从您的代码正确放置在AD上。 So the question is: which table is the child table?那么问题来了:哪个表是子表? Check here for a more extensive answer: Where should I store a foreign key?在这里查看更广泛的答案: Where should I store a foreign key?

Placing the FK on the wrong side, you endanger the integrity of your data.将 FK 放在错误的一边,会危及数据的完整性。

The only other relationship you can create, are both keys on the B table, which means that in order to create a B value you need both A and D .您可以创建的唯一其他关系是 B 表上的两个键,这意味着为了创建B值,您需要同时AD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM