EF 6-在没有反向引用的情况下一对一删除 [英] EF 6 - Cascade Delete on one to many without backreference

查看:92
本文介绍了EF 6-在没有反向引用的情况下一对一删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

public class Gadget {
  public int Id { get; set; }
  public string Name { get; set;}
  public int SuperHeroId { get; set; }
}

public class SuperHero {
  public int Id { get; set; }
  public virtual ICollection<Gadget> Gadgets { get; set; }
}

请注意,尽管小工具归超级英雄所有(因此数据库中存在FK),但我的域模型在该方向上没有硬性参考.

Notice that while a Gadget is "owned" by a Superhero (and therefore there's an FK in the database), my domain model does not have a hard reference in that direction.

当我删除超级英雄时,我还要删除其所有小工具.我该怎么办?

When I delete a superhero I would like to also delete all their gadgets. How would I do this?

我的研究表明,如果我有该参考文献,它将类似于

My research indicates that if I had that reference it would be something like

mapping.Entity<SuperHero>()
  .HasMany(x => x.Gadgets)
  .WithRequired(x => x.SuperHero) //this is the part I can't do
  .WillCascadeOnDelete();

但是请注意,这不适用于我的域模型.

but as noted, that doesn't work with my domain model.

推荐答案

mapping.Entity<SuperHero>()   
       .HasMany(x => x.Gadgets)
       .WithRequired() //use the override that doesn't 
                       //specify a navigation property             
       .WillCascadeOnDelete();

http://msdn.microsoft.com/en-us/library/gg696502(v = vs.113).aspx

将关系配置为可选关系:不需要 关系另一侧的导航属性.

Configures the relationship to be optional:required without a navigation property on the other side of the relationship.

这篇关于EF 6-在没有反向引用的情况下一对一删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆