多对多和一对多关系中的“无法将 NULL 值插入列”错误

问题描述 投票:0回答:1

我得到以下配置:

public class Person
{
    // some default values

    public ICollection<Location> Locations { get; set; }
    public int? LocationId { get; set; }
}

public class Location
{
    // some default values

    public ICollection<Person> Persons{ get; set; }
}

EF Core 中的配置

builder.Entity<Persons>()
       .HasMany(r => r.Locations)
       .WithMany(l => l.Persons)
       .UsingEntity<Dictionary<string, object>>(
                       b => b.HasOne<Location>().WithMany().HasForeignKey("LocationId"),
                       b => b.HasOne<Person>().WithMany().HasForeignKey("PersonId"))
       .ToTable("LocationPersonTable");

我有一对一的关系,但现在我想添加多对多,但我想保留这个一对多的关系值,这可能吗?

使用当前的实现,我收到此错误:

无法将 NULL 值插入表“MyDb.dbo.LocationPersonTable”的“LocationId”列;列不允许为空。插入失败。
该声明已终止。

asp.net-core entity-framework-core many-to-many
1个回答
0
投票

好的,所以您尝试在 Person 和 Location 之间设置多对多,但您还尝试将 FK 添加到 Location within Person。你的设计有点过于复杂了。如果我们可以调整设计以使用多对多和更简化的设计,我认为这也将解决您作为双产品的错误。

这样做:

  1. 从 Person 类中删除 LocationId。

  2. 更新您的 EF Core 配置:

    builder.Entity() .HasMany(p => p.Locations) .WithMany(l => l.Persons) .UsingEntity>( “位置人员表”, b => b.HasOne().WithMany().HasForeignKey("LocationId"), b => b.HasOne().WithMany().HasForeignKey("PersonId"));

您需要创建一个迁移来应用这些更改,因此请确保您有数据库的备份,或者如果它只是测试数据,请将其清除,以免遇到迁移错误。如果您正在进行迁移并且不想丢失数据,请不要忘记备份数据。因为此迁移将从 Person 表中删除 LocationId,并使用正确的外键关系创建 LocationPersonTable。

如果您有任何疑问,请告诉我。这里有可靠的文档来进一步解释。

© www.soinside.com 2019 - 2024. All rights reserved.