Cycle in models in Entity framework core

asp.net-core c# ef-fluent-api entity-framework-core sql-server

Question

Imagine these models are a part of a social network application. User can make a Group and can add other users in it(as members) and a user can be a member of the group. I'm using .net core and also entity framework core.

Models:

public class User : BaseEntity
{
    public string UserName { get; set; }

    public IList<Group> OwnGroups { get; set; }
    public IList<GroupMember> MemberInGroups { get; set; }
}

public class Group : BaseEntity
{
    public string Name { get; set; }
    public int OwnerUserId { get; set; }

    [ForeignKey("OwnerUserId")]
    public User OwnerUser { get; set; }

    public IList<GroupMember> Members { get; set; }
}

public class GroupMember : BaseEntity
{
    public int GroupId { get; set; }
    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }

    [ForeignKey("UserId")]
    public Group Group { get; set; }
}

Fluent API:

    modelBuilder.Entity<User>()
    .HasMany(x => x.OwnGroups)
    .WithOne(x => x.OwnerUser).HasForeignKey(x => x.OwnerUserId).IsRequired().OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<User>()
    .HasMany(x => x.MemberInGroups)
    .WithOne(x => x.User).HasForeignKey(x => x.UserId).IsRequired().OnDelete(DeleteBehavior.Cascade);

modelBuilder.Entity<Group>()
    .HasMany(x => x.Members)
    .WithOne(x => x.Group).HasForeignKey(x => x.GroupId).IsRequired().OnDelete(DeleteBehavior.Cascade);

When I want to migrate to the database, this error happens:

Introducing FOREIGN KEY constraint 'FK_GroupMembers_Users_UserId' on table 'GroupMembers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint or index. See previous errors.

However, I can make this model in SQL Server manually and there is no problem. enter image description here

There are at least two ways to fix it. But I want to know why EF Core says, there is a cycle. What's the problem is?

1
0
7/11/2019 8:21:18 AM

Popular Answer

I think your bridge table has a problem.

Try this

public class GroupMember: BaseEntity
{
public User User { get; set; }
[Key, Column(Order = 0)]
public int UserId { get; set; }

public Group Group { get; set; }
[Key, Column(Order = 1)]
public int GroupId { get; set; }
}
1
7/23/2019 7:42:18 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow