有很多关于这个问题的问题,但我不能解决我的情况。
可以一些请看看这个:
可以一些请看看这个:
我有一个Office表与医生和秘书表有一对多的关系。两个最后的表都是从Employee表派生的,它与sqlmembershipprovider创建的预定义Users表具有共享主键关系。看起来在Users表和Roles表之间有许多关系,我没有任何手。
我的问题是在我的Employee表和用户表之间创建一个(零,一) – (一)关系,我结束了它们之间的共享主键关系和提出的错误。 (有问题的更好的解决方案吗?)
这里是错误:
Introducing FOREIGN KEY constraint
‘FK_dbo.aspnet_UsersInRoles_dbo.aspnet_Users_UserId’ on table
‘aspnet_UsersInRoles’ 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.
public class Office { public Office() { this.Doctors = new HashSet<Doctor>(); this.Secretaries = new HashSet<Secretary>(); } [Key] public System.Guid OfficeId { get; set; } public virtual ICollection<Doctor> Doctors { get; set; } public virtual ICollection<Secretary> Secretaries { get; set; } } public class Employee { [Key,ForeignKey("User")] [DatabaseGenerated(DatabaseGeneratedOption.None)] public System.Guid Id { get; set; } public string Name { get; set; } [ForeignKey("Office")] public System.Guid OfficeId { get; set; } // shared primary key public virtual aspnet_Users User { get; set; } public virtual Office Office { get; set; } } public class Doctor :Employee { public Doctor() { this.Expertises = new HashSet<Expertise>(); } //the rest.. public virtual ICollection<Expertise> Expertises { get; set; } } public class Secretary : Employee { // blah blah } public class aspnet_Users { public aspnet_Users() { this.aspnet_Roles = new List<aspnet_Roles>(); } public System.Guid ApplicationId { get; set; } public System.Guid UserId { get; set; } //the rest.. public virtual aspnet_Applications aspnet_Applications { get; set; } public virtual ICollection<aspnet_Roles> aspnet_Roles { get; set; } } public class aspnet_Roles { public aspnet_Roles() { this.aspnet_Users = new List<aspnet_Users>(); } public System.Guid ApplicationId { get; set; } public System.Guid RoleId { get; set; } //the rest.. public virtual aspnet_Applications aspnet_Applications { get; set; } public virtual ICollection<aspnet_Users> aspnet_Users { get; set; } }
编辑:和关系更深,在用户表和应用程序表之间有一个多对一的关系,也在角色和应用程序之间。
解决方法
您可以使用fluent api指定错误消息建议的操作。
在您的上下文中:
protected override void OnModelCreating( DbModelBuilder modelBuilder ) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<aspnet_UsersInRoles>().HasMany(i => i.Users).Withrequired().WillCascadeOnDelete(false); }
请注意,您没有包括aspnet_UsersInRoles表的定义,因此此代码可能无法正常工作。
另一个选项是通过添加此删除所有CASCADE DELETES
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
如果你需要更多的信息关于配置关系与流利的API,建议http://msdn.microsoft.com/en-US/data/jj591620