我在两个类之间创建了多对多关系。
public class Member
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid MemberId { get; set; }
public string Name { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public Member()
{
Groups = new HashSet<Group>();
}
}
public class Group
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid GroupId { get; set; }
public string Name { get; set; }
public virtual ICollection<Member> Members { get; set; }
public Group()
{
Members = new HashSet<Member>();
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Group>().HasMany(x => x.Members).WithMany(c => c.Groups)
.Map(y =>
{
y.MapLeftKey("GroupId");
y.MapRightKey("MemberId");
y.ToTable("Group_to_Member");
});
}
如果我测试它,这是有效的:
var member = new Member();
member.Name = "Smith";
db.Members.Add(member);
var group = new Group();
group.Name = "Group 1";
db.Groups.Add(group);
member.Groups.Add(group);
group.Members.Add(member);
db.SaveChanges();
但是如何删除组中的成员? 我试过这个: var group = db.Groups.First(); db.Groups.Remove(基); db.SaveChanges();
我只是不断得到“DELETE语句与REFERENCE约束冲突”。 那么我怎么能告诉它先删除关联然后再输入?
答案 0 :(得分:0)
请参阅RedHat关于将数据库中的FK设置为在删除时级联的注释。