我遇到了一个奇怪的问题,我已经知道为什么通常会发生此异常以及如何通过在其中一个属性中将 WillCascadeOnDelete 禁用为 False 来解决它。
但我的问题似乎是其他类型的,这是我的代码:
会员:
public class Memeber
{
public int MemberID { get; set; }
public virtual ICollection<Message> SentMessages { get; set; }
public virtual ICollection<Message> RecievedMessages { get; set; }
}
public class Message
{
public long MessageID { get; set; }
public int SenderMemberId{ get; set; }
public virtual ICollection<Member> RecipientsMembers { get; set; }
[ForeignKey("SenderMemberId")]
public virtual Member SenderMember { get; set; }
}
这是映射:在消息配置中:
this.HasRequired(c => c.SenderMember)
.WithMany(c => c.SentMessages)
.HasForeignKey(c => c.SenderMemberId)
.WillCascadeOnDelete(false);
在 MemberConfiguration 中:
this.HasMany(c => c.RecievedMessages)
.WithMany(c => c.RecipientsMembers)
.Map(cm =>
{
cm.ToTable("MessageJoinMemeber");
cm.MapLeftKey("MessageId");
cm.MapRightKey("MemberId");
});
如您所见,一条消息包含一个具有 ForeignKey SenderID 的发件人,一对多双向。成员有 2 个消息列表,一个作为接收者,一个作为发送者。我试图在其中一个关系(第一个)中禁用删除级联,但我仍然从 SQL 引擎中遇到同样的问题。我也尝试从消息部分定义关系,而不是从成员部分定义关系:
this.HasMany(c => c.RecipientsMembers)
.WithMany(c=> c.RecievedMessages)
.Map ( cm =>
{
cm.ToTable("MessageJoinMemeber");
cm.MapLeftKey("MessageId");
cm.MapRightKey("MemberId");
});
但总是我得到这个错误:
System.Data.SqlClient.SqlException was unhandled by user code
HResult=-2146232060
Message=Introducing FOREIGN KEY constraint 'FK_dbo.MessageJoinMemeber_dbo.Messages_MemberId' on table 'MessageJoinMemeber' 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.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=1785
Procedure=""
Server=KINGPC
State=0
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)