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