How to lower number of queries that EF4 sends to DB?
I use the following code to remove all KlientDoTrasa assigned to trasaOriginal and then create and assign new KlientDoTrasa based on collection: trasaToEdit.Klienci. In my test case assigned KlientDoTrasa and new KlientDoTrasa are the same, so I thought EF4 should not send any query to database, but it sends, first deletes then inserts. Is there a way to limit it?
public void Edit(int trasaId, TrasaEditViewModel trasaToEdit)
{
Trasa trasaOriginal = _trasaRepository.FindById(trasaId);
trasaOriginal.Nazwa = trasaToEdit.Trasa.Nazwa;
foreach(KlientDoTrasa kdt in trasaOriginal.KlientDoTrasa.ToList())
{
_klientDoTrasaRepositor开发者_开发技巧y.Remove(kdt);
}
for(int i = 0; i < trasaToEdit.Klienci.Count; i++)
{
var kdt = new KlientDoTrasa {Trasa = trasaOriginal, KlientId = trasaToEdit.Klienci[i].Id, Seq = i};
_klientDoTrasaRepository.Add(kdt);
}
_klientDoTrasaRepository.SaveChanges();
_trasaRepository.SaveChanges();
}
Entity Framework does not do a deep comparison of your entities to determine whether they are equivalent. Your code above will delete then insert, assuming that the two entities are different.
If you want to avoid updating an Entity that hasn't changed, you'll need to check for that in your own logic. I believe you could use a partial class declaration to implement IEqualityComparer for your entities, then compare before submit.
精彩评论