2
更新操作過程中設置EntityState.Modified假設我有一個使用實體框架5以下的小控制檯應用程序:與實體框架
class Program {
static void Main(string[] args) {
using (var ctx = new ConfContext()) {
var personBefore = ctx.People.First();
Console.WriteLine(personBefore.Name);
personBefore.Name = "Foo2";
ctx.SaveChanges();
var personAfter = ctx.People.First();
Console.WriteLine(personAfter.Name);
}
Console.ReadLine();
}
}
public class ConfContext : DbContext {
public IDbSet<Person> People { get; set; }
public IDbSet<Session> Sessions { get; set; }
}
public class Person {
[Key]
public int Key { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDate { get; set; }
public ICollection<Session> Sessions { get; set; }
}
public class Session {
[Key]
public int Key { get; set; }
public int PersonKey { get; set; }
public string RoomName { get; set; }
public string SessionName { get; set; }
public Person Person { get; set; }
}
正如你所看到的,我改變了記錄的名稱和保存它。它的作品,但它感覺像我的魔力。我在做什麼在我所有的應用程序是下面一個(更準確,我的通用存儲庫的編輯方法中):
static void Main(string[] args) {
using (var ctx = new ConfContext()) {
var personBefore = ctx.People.First();
Console.WriteLine(personBefore.Name);
personBefore.Name = "Foo2";
var entity = ctx.Entry<Person>(personBefore);
entity.State = EntityState.Modified;
ctx.SaveChanges();
var personAfter = ctx.People.First();
Console.WriteLine(personAfter.Name);
}
Console.ReadLine();
}
毫無疑問的是,第二個是更多的語義,但有沒有任何其他明顯的差異?
謝謝!我從你的答案中得到的結果是:當你明確使用DbContext並知道實體已連接時,不要設置它。例如,當您在通用存儲庫中具有編輯方法時,可以安全地進行設置。 – tugberk
是的,這是一個很好的用例 – devdigital