skip to Main Content

I have problem with EntityFramework relationships. I want to create a relationship between User, Restaurant and Menu Item, the question is why is the Entity Framework screaming even though I have added an optional "int?" to the UserId property? After update-database command I get an error "The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_Restaurants_Users_UserId".. Cannot insert the value NULL into column ‘UserId’, table ‘FoodHost.dbo.Restaurants’; column does not allow nulls."

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);
    }

2

Answers


  1. Cannot insert the value NULL into column ‘UserId’, table ‘FoodHost.dbo.Restaurants’; column does not allow nulls."

    That’s clearly telling you that Restraunts.UserId does not allow nulls. So your model and your database don’t match.

    Login or Signup to reply.
  2. Consider using a many-to-many join table for Users of Restaurants:

    public class Restaurant
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public List<MenuItem> MenuItems { get; set; } = new List<MenuItem>();
    }
    public class MenuItem
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
    }
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; } = string.Empty;
        public List<Restaurant> Restaurants { get; set; } = new();
    }
    public class RestaurantUser
    {
        public int RestaurantId { get; set; }
        public int UserId { get; set; }
        public List<Restaurant> Restaurants { get; set; } = new();
        public List<User> Users { get; set; } = new();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search