我在实体框架6中建立关系并使级联删除工作时遇到问题。
我有以下对象
public class Module {
public long Id { get; set; };
public virtual ICollection<Group> Groups { get; set; };
}
public class Group {
public long Id { get; set; };
public virtual ICollection<Field> Fields { get; set; };
}
public class Field {
public long Id { get; set; };
public virtual FieldLink Link { get; set; };
}
public class FieldLink {
public long Id { get; set; };
public virtual Module LinkToModule { get; set; };
}
现在一个模块有组,一个组有字段,一个字段可以有一个链接。链接将具有LinkToModule,但这可以是与父字段/组所属的模块不同的模块。
我已经建立了我的关系
public ModuleConfig()
{
this.ToTable("Module");
}
public FieldGroupConfig()
{
this.ToTable("FieldGroup");
// relationships
this.HasRequired(e => e.Module)
.WithMany(e => e.Groups)
.HasForeignKey(e => e.ModuleId);
}
public FieldConfig()
{
this.ToTable("Field");
this.HasRequired(e => e.FieldGroup)
.WithMany(e => e.Fields)
.HasForeignKey(e => e.FieldGroupId);
this.HasOptional(e => e.Link)
.WithRequired(e => e.Field);
}
public FieldLinkConfig()
{
this.ToTable("FieldLink");
this.HasRequired(e => e.LinkToModule)
.WithMany()
.HasForeignKey(e => e.LinkToModuleId);
}
现在我正在运行我的测试,我收到以下错误
Test method ModuleServiceTests.ModuleService_DeleteAsync_ByEntity threw exception:
System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.FieldLink_dbo.Field_Id". The conflict occurred in database "TestDb", table "dbo.FieldLink", column 'Id'.
如果我检查关系,它就在表Field.Id&gt;之间。 FieldLink.Id和DELETE规则设置为NO ACTION。很好,所以我想我需要更新该关系并使用WillCascadeOnDelete(true)
所以我从
更新了FieldConfig中的代码this.HasOptional(e => e.Link)
.WithRequired(e => e.Field);
到
this.HasOptional(e => e.Link)
.WithRequired(e => e.Field)
.WillCascadeOnDelete(true);
但是现在当我尝试运行我的测试时,数据库甚至没有创建,我得到的错误是
Initialization method Test.TestInitialize threw exception.
System.Data.SqlClient.SqlException: Introducing FOREIGN KEY constraint 'FK_dbo.FieldLink_dbo.Field_Id' on table 'FieldLink' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
有人可以帮忙吗?我是否错误地设置了一段关系,我是否对此采取了错误的方式?