Entity Framework 4 Partialy SaveChanges

2019-08-10 22:24发布

问题:

Lets say i have this:

var entity = db.histories.GetWhere(x => x.Body == "MyBody").FirstOrDefault();
var entity2 = db.histories.GetWhere(x => x.Body == "MyBody2").FirstOrDefault();
        entity.From = "lmao!";
        entity2.From = "lmao2!";

now i know that to update i have to call db.SaveChanges();

my question is what if i want to update entity only and not entity2 ?

is that even possible ? could be simple im not sure.

thanks in advance.

回答1:

Either get the 2 entities from separate contexts:

var entity = db.histories.GetWhere(x => x.Body == "MyBody").FirstOrDefault();
var entity2 = differentDbInstance.histories.GetWhere(x => x.Body == "MyBody2").FirstOrDefault();        

or retrieve from the same context but detach before making changes you dont want saved

db.Detach(entity2);
entity2.From = "lmao2!";

The latter is better design but you may need to former depending on the scenario



回答2:

This has been asked before, and no, there is no way to accomplish this.

entity and entity2 would have to be on different data contexts to achieve what you're looking for.