Ef-CodeFirst外键失败
本文关键字:失败 Ef-CodeFirst | 更新日期: 2023-09-27 18:27:40
我有一个带有以下类的代码优先迁移项目:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Chat> Chats { get; set; }
}
和
public class Chat
{
[Key, Column(Order = 0)]
public int User1Id { get; set; }
public virtual User User1 { get; set; }
[Key, Column(Order = 1)]
public int User2Id { get; set; }
public virtual User User2 { get; set; }
public string Channel { get; set; }
}
想法是聊天有两个用户,聊天主键是两个用户ID的复合密钥,这两个ID是外键。
用户还有一个他参与的聊天列表。
现在,当我尝试运行这个时,我得到以下错误:
Introducing FOREIGN KEY constraint 'FK_dbo.Chat_dbo.User_User2Id' on table 'Chat' 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. See previous errors.
我有点理解发生了什么,但我不知道如何解决它。尝试过这个(从这里的某个主题):
public DbSet<User> Users { get; set; }
public DbSet<Chat> Chats { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Chat>()
.HasRequired(s => s.User1)
.WithMany()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Chat>()
.HasRequired(s => s.User2)
.WithMany()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
但是没有结果,我还是犯了错误。有人能阐明这件事吗?
尝试
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Chat> InitiatedChats { get; set; }
public virtual ICollection<Chat> ParticipantInChats { get; set; }
}
public class Chat
{
[Key, Column(Order = 0)]
public int User1Id { get; set; }
public virtual User User1 { get; set; }
[Key, Column(Order = 1)]
public int User2Id { get; set; }
public virtual User User2 { get; set; }
public string Channel { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Chat>()
.HasRequired(s => s.User1)
.WithMany(u => u.InitiatedChats)
.HasForeignKey(s => s.User1Id)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Chat>()
.HasRequired(s => s.User2)
.WithMany(u => u.ParticipantInChats)
.HasForeignKey(s => s.User2Id)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
anwser来自这篇文章