得到";外键约束";即使级联删除被关闭
本文关键字:quot 删除 级联 约束 得到 | 更新日期: 2023-09-27 18:01:09
我有以下用户模型:
public class User
{
public Guid Id { get; set; }
[ForeignKey("Location")]
public Guid LocationId { get; set; }
public Location Location { get; set; }
[ForeignKey("MainPhoneNumber")]
public Guid? MainPhoneNumberId { get; set; }
[ForeignKey("Mailbox")]
public Guid? MailboxId { get; set; }
[ForeignKey("Fax")]
public Guid? FaxId { get; set; }
[MaxLength(50)]
public string UserName { get; set; }
[ForeignKey("Conference")]
public Guid? ConferenceId { get; set; }
public virtual PhoneNumber MainPhoneNumber { get; set; }
public virtual PhoneNumber Mailbox { get; set; }
public virtual PhoneNumber Fax { get; set; }
public virtual PhoneNumber Conference { get; set; }
public virtual ICollection<AddOn> AddOns { get; set; }
}
我还使用Fluent Api添加了以下规则:
modelBuilder.Entity<User>()
.HasRequired(usr=>usr.Location)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(usr => usr.Fax)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(usr => usr.Conference)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(usr => usr.Mailbox)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasOptional(usr => usr.MainPhoneNumber)
.WithMany()
.WillCascadeOnDelete(false);
我希望这些流畅的规则能帮助我解决任何Cascade删除问题。但当我试图在控制台内运行"Update-Database
"时,仍然收到以下错误:
引入FOREIGN KEY约束"FK_dbo.User_dbo.PhoneNumber_FaxId"在表"User"上,可能会导致循环或多个级联路径。指定ONDELETE NO ACTION或ON UPDATE NO ACTION,或修改其他外键约束。无法创建约束。请参阅以前的错误。
注意:请注意这不是该问题的重复:引入FOREIGN KEY约束可能会导致循环或多个级联路径-为什么?
正如你所看到的:在投票最多的答案中提出的建议已经包含在我的代码中(Fluent部分(
(更新(这是电话号码类别:
public class PhoneNumber
{
public Guid Id { get; set; }
[ForeignKey("PhoneNumberPool")]
public Guid PhoneNumberPoolId { get; set; }
public virtual PhoneNumberPool PhoneNumberPool { get; set; }
public int Length { get; set; }
}
PhoneNumberPool本身有一些简单的属性(string、int等(和对"Location"(以及User(的引用。
这个数据模型能为您工作吗?
这样你就可以添加新类型的电话号码
public enum PhoneNumberType {Main, Mailbox, Fax, Conference, Other}
PhoneNumber{
public PhoneNumberType NumberType{get;set;};
public string Number{get;set;};
//other properties
public virtual User{get;set;}
}
public class User
{
public Guid Id { get; set; }
[ForeignKey("Location")]
public Guid LocationId { get; set; }
public Location Location { get; set; }
[MaxLength(50)]
public string UserName { get; set; }
public virtual List<PhoneNumber> PhoneNumbers { get; set; }
public virtual ICollection<AddOn> AddOns { get; set; }
}