0
我的代碼工作正常,直到我添加了WillCascadeOnDelete(true)。一對多級聯刪除沿多對多原因異常
異常:InvalidOperationException - 數據庫創建成功,但創建的數據庫對象沒有。有關更多詳情,請參閱內部例外
內部異常:System.Data.SqlServerCe.SqlCeException - 參照關係將導致不允許的循環引用。 [約束名= User_AdministratorOf_Target]
最小再現(在一個新的MVC3的Web應用程序項目):
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
public class User
{
[Key]
public string UserName { get; set; }
public virtual ICollection<Document> Documents { get; set; }
public virtual ICollection<Document> AdministratorOf { get; set; }
}
public class Document
{
public int Id { get; set; }
public User Owner { get; set; }
public ICollection<User> Administrators{ get; set; }
}
public class EntityMappingContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Document> Documents { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasMany(x => x.AdministratorOf)
.WithMany(x => x.Administrators)
.Map(x =>
{
x.MapLeftKey("UserName");
x.MapRightKey("Document");
x.ToTable("DocumentAdministrators");
});
modelBuilder.Entity<Document>()
.HasRequired(x => x.Owner)
.WithMany(x => x.Documents)
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
還必須添加SQL連接字符串下當然的ConnectionStrings到Web.config中:
<add name="EntityMappingContext" connectionString="Data Source=|DataDirectory|Error.sdf" providerName="System.Data.SqlServerCe.4.0"/>
在一對多關係已經存在的情況下,如何在刪除時啓用級聯創建循環關係?是否說在級聯刪除中有一個循環?如何,當我指定的唯一級聯是用戶 - >文檔?我如何解決它?謝謝!