我正在进行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; }
}
&#13;
在.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; }
}
&#13;
我正在尝试Delete on cascade
...当我删除一个组时,我想要删除该组中的所有成员。
所以在OnModelCreating
Context.cs
文件中我添加了everthing,我发现为了在级联上删除,但没有任何工作。
这是我到目前为止所尝试的内容。
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);
&#13;
以下是我用来删除它的代码。
var master = _db.Set<Groups>().Include(m => m.GroupMembers).SingleOrDefault(m => m.Group_id == 2);
_db.Set<Groups>().Remove(master);
_db.SaveChanges();
&#13;
我有以下错误......
"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."
&#13;
似乎没有尝试删除子记录。它试图用Null更新
如何正确地做到这一点。?
答案 0 :(得分:0)
我用这段代码解决了。它不是我想要的级联,但它是我发现的最佳方式。
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();
}
&#13;