我正在做一个MVC
Entity Framework 6
DataBase First
应用程序。
我有两张桌子.. Groups
和MemberGroups
,具有一对多的关系。
Foreign Key can not be Null
当我将数据库添加到我的应用程序时。.Edmx
是用Context.cs
文件生成的
public partial class PortalEntities : DbContext
{
public VIvaVoceEntities()
: base("name=PortalEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<GroupMembers> GroupMembers { get; set; }
public virtual DbSet<Groups> Groups { get; set; }
}
在.tt
文件夹下,为每个表生成了class
。
public partial class Groups
{
public long Group_id { get; set; }
public string Name { get; set; }
public virtual ICollection<GroupMembers> GroupMembers { get; set; }
}
public partial class GroupMembers
{
public long MemberGroup_ID { get; set; }
public long Group_id { get; set; }
}
我正在尝试做一个Delete on cascade
...删除组时,我想删除该组中的所有成员。因此,在OnModelCreating
Context.cs
文件中,我添加了我找到的所有内容,以便在级联中删除,但没有任何效果。
这是我到目前为止尝试过的。
modelBuilder.Entity<Groups>()
.HasMany(e => e.GroupMembers)
.WithRequired(e => e.Groups)
.WillCascadeOnDelete(true);
---------------------------------
modelBuilder.Entity<Groups>()
.HasOptional(x => x.GroupMembers)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
---------------------------------
modelBuilder.Entity<Groups>().HasMany(i => i.GroupMembers)
.WithOptional(i => i.Groups)
.HasForeignKey(i => i.Group_id)
.WillCascadeOnDelete(true);
---------------------------------
modelBuilder.Entity<Groups>()
.HasRequired(e => e.GroupMembers)
.WithMany()
.HasForeignKey(e => e.Group_id )
.WillCascadeOnDelete(true);
这是我用来删除它的代码。
var master = _db.Set<Groups>().Include(m => m.GroupMembers).SingleOrDefault(m => m.Group_id == 2);
_db.Set<Groups>().Remove(master);
_db.SaveChanges();
我有以下错误...
"The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted."
似乎它没有尝试删除子记录。它正在尝试使用空更新
正确的方法是什么。?
我用这段代码解决了。它不是我想要的级联,但这是我找到的最好的方法。
public void Delete(long Group_id)
{
Groups group = _db.Set<Groups>().Include(m => m.GroupMembers).SingleOrDefault(m => m.Group_id == Group_id);
_db.GroupMembers.RemoveRange(group.GroupMembers);
_db.SaveChanges();
_db.Entry(group).State = System.Data.Entity.EntityState.Deleted;
_db.SaveChanges();
}