EF 6 - Cascade Delete on one to many without backreference

一个人想着一个人 提交于 2019-12-07 00:13:22

问题


I have something like this:

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; }
}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/20577433/ef-6-cascade-delete-on-one-to-many-without-backreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!