2014-10-01 63 views
1

我有UserProfile他们有1-1关系的实体。
MVC Code First - 级联删除1对1的关系

用户实体和配置

public class User 
{ 
    public int ID { get; set; } 
    public virtual Profile Profile { get; set; } 
} 

public class UserConfig : EntityTypeConfiguration<User> 
{ 
    public UserConfig() 
    { 
     HasRequired(x => x.Profile).WithRequiredPrincipal(x => x.User); 
    } 
} 

档案实体和CONFIGS

public class Profile 
{ 
    public int ID { get; set; } 
    public virtual User User { get; set; } 
} 

public class ProfileConfig : EntityTypeConfiguration<Profile> 
{ 
    public ProfileConfig() 
    { 
     HasRequired(x => x.User).WithRequiredDependent(x => x.Profile).Map(x => x.MapKey("UserID")).WillCascadeOnDelete(true); 
    } 
} 

然而,当我尝试删除用户我得到下面这个异常的列表:

List<User> users = _user.Where(x => m.SelectedUsersID.Contains(x.ID)).ToList(); 
users.ForEach(x => _user.Remove(x)); 

A relationship from the 'Profile_User' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Profile_User_Source' must also in the 'Deleted' state.

我有不知道什么是错的,请帮助:)

回答

0

好吧,我可以通过删除这两个实体来解决这个问题。这意味着我不得不删除ProfileUser二者

users.ForEach(x => _profile.Remove(x.Profile)); 
users.ForEach(x => _user.Remove(x)); 
0

您删除用户,但用户未配置为级联删除。这意味着配置文件不会被删除并且违反数据库的完整性。 EF会阻止数据库并因此引发错误。

您应该配置为级联删除。

+0

我尝试了这个太:'HasRequired(X => x.Profile).WithRequiredPrincipal(X => x.User).WillCascadeOnDelete(真);'但我仍然有同样的错误。 无论如何,我找到了答案,并在上面写道,非常感谢 – mhesabi 2014-10-01 06:20:31