1

When I create new entities in a context, I cannot get a proxy even if I request it again. I have to dispose of the context and make a new one. Is this an expected behavior or am I doing something wrong?

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!
}
Pluc
  • 2,909
  • 1
  • 22
  • 36
  • 2
    Instead of `People.Add(new ...)`, try using `People.Create()`. This should give you a proxy if your POCO is defined to support proxy objects. – Asad Saeeduddin Feb 09 '15 at 22:11

2 Answers2

3

You can use the Create method of your DBSet:

var newPerson=context.People.Create();

The instance returned will be a proxy if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.

Update

As @Asad said, if you are creating a new entity, you need to add it to your DBSet after creating it:

context.People.Add(newPerson);

Or change its State to Added, for example:

context.Entry(newPerson).State = EntityState.Added; 

And, if you are updating it, then you should use Attach method:

var existingPerson=context.People.Create();
existingPerson.Id = 1; // assuming it exists in the DB
context.People.Attach(existingPerson);
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • 1
    It is worth noting that the instance returned by `Create` is not automatically a member of the `DbSet`. This is an additional step that needs to be explicitly performed by `Attach`ing or `Add`ing it (depending on whether it is a new or existing entity). – Asad Saeeduddin Feb 09 '15 at 22:17
2

octavioccl's answer is correct but would force me to break my data layer pattern. I have an alternative (probably slower) solution that didn't force me to create the entity inside my repository nor required me to add mapping everywhere (or a mapping library). I am still accepting your answer since it probably is closer to best practice and did answer the original question but I wanted to add this option if ever needed.

dbContext.People.Add(person);
dbContext.SaveChanges();
dbContext.Entry(person).State = EntityState.Detached;
dbContext.People.Find(person.Id);
Pluc
  • 2,909
  • 1
  • 22
  • 36