我正在使用Entity Framework Core和Code First方法,但在更新数据库时收到以下错误:
在表'AnEventUsers'上引入FOREIGN KEY约束'FK_AnEventUsers_Users_UserId'可能会导致循环或多个级联路径.指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束.无法创建约束或索引.查看以前的错误.
我的实体是:
public class AnEvent { public int AnEventId { get; set; } public DateTime Time { get; set; } public Gender Gender { get; set; } public int Duration { get; set; } public Category Category { get; set; } public int MinParticipants { get; set; } public int MaxParticipants { get; set; } public string Description { get; set; } public Status EventStatus { get; set; } public int MinAge { get; set; } public int MaxAge { get; set; } public double Longitude { get; set; } public double Latitude { get; set; } public ICollectionAnEventUsers { get; set; } public int UserId { get; set; } public User User { get; set; } } public class User { public int UserId { get; set; } public int Age { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Gender Gender { get; set; } public double Rating { get; set; } public ICollection AnEventUsers { get; set; } } public class AnEventUser { public int AnEventId { get; set; } public AnEvent AnEvent { get; set; } public int UserId { get; set; } public User User { get; set; } } public class ApplicationDbContext:DbContext { public ApplicationDbContext(DbContextOptions options):base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity () .HasOne(u => u.User).WithMany(u => u.AnEventUsers).IsRequired().OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity () .HasKey(t => new { t.AnEventId, t.UserId }); modelBuilder.Entity () .HasOne(pt => pt.AnEvent) .WithMany(p => p.AnEventUsers) .HasForeignKey(pt => pt.AnEventId); modelBuilder.Entity () .HasOne(eu => eu.User) .WithMany(e => e.AnEventUsers) .HasForeignKey(eu => eu.UserId); } public DbSet Events { get; set; } public DbSet Users { get; set; } public DbSet AnEventUsers { get; set; } }
我想的问题是,如果我们删除User,将删除对AnEvent的引用,并且还将删除对AnEventUser的引用,因为AnEvent引用了AnEventUser,我们也获得了级联路径.但我删除了从User到AnEventUser的删除级联:
modelBuilder.Entity() .HasOne(u => u.User).WithMany(u => u.AnEventUsers).IsRequired().OnDelete(DeleteBehavior.Restrict);
但是错误没有得到解决,有人看到了什么问题吗?谢谢!
在您的示例代码中,OnModelCreating
您已经声明了modelBuilder.Entity
两次:在方法开始时和结束时.
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() // THIS IS FIRST .HasOne(u => u.User).WithMany(u => u.AnEventUsers).IsRequired().OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity () .HasKey(t => new { t.AnEventId, t.UserId }); modelBuilder.Entity () .HasOne(pt => pt.AnEvent) .WithMany(p => p.AnEventUsers) .HasForeignKey(pt => pt.AnEventId); modelBuilder.Entity () // THIS IS SECOND. .HasOne(eu => eu.User) // THIS LINES .WithMany(e => e.AnEventUsers) // SHOULD BE .HasForeignKey(eu => eu.UserId); // REMOVED }
第二次调用首先覆盖.去掉它.