EF Core 1.1多对多关系(ON删除无操作或更新无操作)

时间:2017-01-22 11:32:33

标签: c# .net entity-framework-core

我试图创建一个具有多对多关系的模型:

  • 公司可以拥有0个或更多用户

  • 公司可以有0个或更多角色

  • 用户和角色之间的多对多关系

每当我尝试创建数据库(update-database)时,我都会收到消息:

介绍FOREIGN KEY约束' FK_UsersRoles_Users_UserId'在桌面' UsersRoles'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。

我不明白它所指的周期。我的意思是,如果我删除了一个用户,它必须删除UsersRoles中的实体,仅此而已。如果我删除一个角色也一样。

如果我的模型只有用户和角色,没有公司表,则会创建数据库。

我做错了什么?

public class MyContext : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = ConsoleApp1; Trusted_Connection = True; MultipleActiveResultSets = true");

        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserRole>()
            .ToTable("UsersRoles")
            .HasKey(t => new { t.UserId, t.RoleId });

        modelBuilder.Entity<UserRole>()
            .HasOne(pt => pt.User)
            .WithMany(p => p.UsersRoles)
            .HasForeignKey(pt => pt.UserId);

        modelBuilder.Entity<UserRole>()
            .HasOne(pt => pt.Role)
            .WithMany(t => t.UsersRoles)
            .HasForeignKey(pt => pt.RoleId);

        base.OnModelCreating(modelBuilder);
    }
}

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<User> Users { get; set; }
    public ICollection<Role> Roles { get; set; }
}

public class User
{
    public int Id { get; set; }
    public string Surname { get; set; }
    public int CompanyId { get; set; }
    public Company Company { get; set; }
    public ICollection<UserRole> UsersRoles { get; set; }
}

public class Role
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyId { get; set; }
    public Company Company { get; set; }
    public ICollection<UserRole> UsersRoles { get; set; }
}

public class UserRole
{
    public int UserId { get; set; }
    public User User { get; set; }
    public int RoleId { get; set; }
    public Role Role { get; set; }
}

0 个答案:

没有答案