UPDATE 语句与 FOREIGN KEY 约束“FK_Restaurants_Users_UserId”冲突

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

我对 EntityFramework 关系有问题。我想在用户、餐厅和菜单项之间创建关系,问题是为什么实体框架尖叫,即使我添加了可选的“int?”到 UserId 属性?在 update-database 命令之后,我收到错误“UPDATE 语句与 FOREIGN KEY 约束“FK_Restaurants_Users_UserId”冲突。无法将 NULL 值插入表“FoodHost.dbo.Restaurants”列“UserId”中;列不允许空值。 ”

public class Restaurant
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int? UserId { get; set; }
    public User User { get; set; }
    public List<MenuItem> MenuItems { get; set; } = new List<MenuItem>();
}

public class User
{
    public int Id { get; set; }
    public string UserName { get; set; } = string.Empty;
    public List<Restaurant> Restaurants { get; set; } = new();
}

 public class MenuItem
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int? RestaurantId { get; set; }
    public Restaurant Restaurant { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>()
            .HasMany(u => u.Restaurants)
            .WithOne(r => r.User)
            .HasForeignKey(r => r.UserId)
            .OnDelete(DeleteBehavior.NoAction);

        modelBuilder.Entity<Restaurant>()
            .HasMany(r => r.MenuItems)
            .WithOne(mi => mi.Restaurant)
            .HasForeignKey(mi => mi.RestaurantId)
            .OnDelete(DeleteBehavior.NoAction);
    }
c# asp.net .net entity-framework entity-framework-core
1个回答
0
投票

无法将 NULL 值插入表“FoodHost.dbo.Restaurants”的“UserId”列;列不允许为空。”

这清楚地告诉您 Restraunts.UserId 不允许为空。所以你的模型和数据库不匹配。

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