Code-First模型:
public class Princess
{
public int Id { get; set; }
public virtual ICollection<Unicorn> Unicorns { get; set; }
}
public class Unicorn
{
public int Id { get; set; }
public virtual ICollection<Princess> Princesses { get; set; }
}
是否可以在没有加载(急切或懒惰)所有集合数据的情况下从集合中删除实体?
var princess = context.Princesses.Where(x => x.Id == 1).Single();
var unicorn = context.Unicorns.Where(x => x.Id == 1).Single();
princes.Unicorns.remove(unicorn); //load all assigned unicorns
context.SaveChanges();
我猜ExecuteSqlCommand应该可以工作。其他解决方案?
答案 0 :(得分:1)
使用存根。在我的头顶(可能需要调整):
var princess = new Princess { Id = 1 };
princess.Unicorns.Add(new Unicorn { Id = 1 });
context.Princesses.Attach(princess); // start tracking changes
princes.Unicorns.Remove(unicorn);
context.SaveChanges();