我怎样才能用他们的代理获得新创建的实体?
How can I get newly created entities with their proxy?
当我在上下文中创建新实体时,即使我再次请求也无法获得代理。我必须处理上下文并创建一个新的。这是预期的行为还是我做错了什么?
int id = 0;
using (var context = new MyContext())
{
var A = context.People.Add(new Person{ Name = "Bob" }); // A is not a proxy
context.SaveChanges(); // A is still not a proxy
var B = context.People.Where(o => o.Id == A.Id).Single(); // B is not a proxy
id = A.Id; // Keep the ID to use with a new context
}
using (var context = new MyContext())
{
var C = context.People.Where(o => o.Id == id).Single(); // C is a proxy!
}
您可以使用 DBSet 的 Create
方法:
var newPerson=context.People.Create();
如果底层上下文配置为创建代理且实体类型满足 requirements for creating a proxy.
,则返回的实例将是代理
更新
正如@Asad 所说,如果您正在创建一个新实体,则需要在创建后将其添加到您的 DBSet 中:
context.People.Add(newPerson);
或者将其State改为Added
,例如:
context.Entry(newPerson).State = EntityState.Added;
而且,如果你正在更新它,那么你应该使用 Attach
方法:
var existingPerson=context.People.Create();
existingPerson.Id = 1; // assuming it exists in the DB
context.People.Attach(existingPerson);
octavioccl 的回答是正确的,但会迫使我打破我的数据层模式。我有一个替代(可能更慢)的解决方案,它不会强迫我在我的存储库中创建实体,也不需要我在任何地方添加映射(或映射库)。我仍然接受您的回答,因为它可能更接近最佳实践并且确实回答了原始问题,但我想在需要时添加此选项。
dbContext.People.Add(person);
dbContext.SaveChanges();
dbContext.Entry(person).State = EntityState.Detached;
dbContext.People.Find(person.Id);
当我在上下文中创建新实体时,即使我再次请求也无法获得代理。我必须处理上下文并创建一个新的。这是预期的行为还是我做错了什么?
int id = 0;
using (var context = new MyContext())
{
var A = context.People.Add(new Person{ Name = "Bob" }); // A is not a proxy
context.SaveChanges(); // A is still not a proxy
var B = context.People.Where(o => o.Id == A.Id).Single(); // B is not a proxy
id = A.Id; // Keep the ID to use with a new context
}
using (var context = new MyContext())
{
var C = context.People.Where(o => o.Id == id).Single(); // C is a proxy!
}
您可以使用 DBSet 的 Create
方法:
var newPerson=context.People.Create();
如果底层上下文配置为创建代理且实体类型满足 requirements for creating a proxy.
,则返回的实例将是代理更新
正如@Asad 所说,如果您正在创建一个新实体,则需要在创建后将其添加到您的 DBSet 中:
context.People.Add(newPerson);
或者将其State改为Added
,例如:
context.Entry(newPerson).State = EntityState.Added;
而且,如果你正在更新它,那么你应该使用 Attach
方法:
var existingPerson=context.People.Create();
existingPerson.Id = 1; // assuming it exists in the DB
context.People.Attach(existingPerson);
octavioccl 的回答是正确的,但会迫使我打破我的数据层模式。我有一个替代(可能更慢)的解决方案,它不会强迫我在我的存储库中创建实体,也不需要我在任何地方添加映射(或映射库)。我仍然接受您的回答,因为它可能更接近最佳实践并且确实回答了原始问题,但我想在需要时添加此选项。
dbContext.People.Add(person);
dbContext.SaveChanges();
dbContext.Entry(person).State = EntityState.Detached;
dbContext.People.Find(person.Id);