在我添加 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);
}
}
当然,还必须在 connectionStrings 下将 SQL 连接字符串添加到 web.config 中:
<add name="EntityMappingContext" connectionString="Data Source=|DataDirectory|Error.sdf" providerName="System.Data.SqlServerCe.4.0"/>
当一对多关系已经存在时,删除时启用级联如何创建循环关系?是不是说级联删除有循环?当我指定的唯一级联是用户 - >文档时,如何?我如何解决它?谢谢!