public void Delete(Dinner dinner)
{
List<RSVP> rsvps = dinner.RSVPs.ToList();// This clone looks inefficient.
foreach (RSVP rsvp in rsvps)
entities.RSVPs.DeleteObject(rsvp);
entities.Dinners.DeleteObject(dinner);
}
问题:
通过删除通过子行克隆首先引用它的子行来删除父行看起来效率低下。
我认为复制子行会占用大量资源。
如果是,那么更好的方法是什么?
编辑1:
namespace NerdDinner.Models
{
public class DinnerRepository
{
private NerdDinnerEntities entities = new NerdDinnerEntities();
public IQueryable<Dinner> FindAllDinners()
{
return entities.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in entities.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinnerByID(int DinnerID)
{
return entities.Dinners.FirstOrDefault(d => d.DinnerID == DinnerID);
}
public void Add(Dinner dinner)
{
entities.Dinners.AddObject(dinner);
}
public void Delete(Dinner dinner)
{
//List<RSVP> rsvps = dinner.RSVPs.ToList();
//foreach (RSVP rsvp in dinner.RSVPs)
// entities.RSVPs.DeleteObject(rsvp);
entities.Dinners.DeleteObject(dinner);
}
public void Save()
{
entities.SaveChanges();
}
}
}
答案 0 :(得分:1)
将删除规则设置为在外键上级联,然后当您删除晚餐对象时,数据库将自动删除所有子记录。
请记住,这可能不会反映到EF,因此内存中已有的任何对象都不会被标记为已删除。