Base solution for your next web application
Open Closed

Reload Instance from Database after Inserted #1255


User avatar
0
andis created

From EntityFramework side, after we insert a POCO, all navigational properties are still null. I found some solutions mentioned that i need to detach and find again to refresh the object or using DbSet.Create to create my entity instead using POCO constructor. But currently I am unable to access either DbContext or DbSet from Repository. How to reload the instance in aspboilerplate? or how to access DbContext or DbSet?


4 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    Did you try this:

    1. Create and Insert entity to repository.
    2. Save changes (<a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work#DocUowSaveChanges">http://www.aspnetboilerplate.com/Pages/ ... aveChanges</a>) - in application service, use CurrentUnitOfWork.SaveChanges (or SaveChangesAsync if your method is async).
    3. Use repository.Get() by Id.

    I haven't tried, but probably it will be like you want after getting from repository. If not;

    • Create a custom repository method (<a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/EntityFramework-Integration#DocCustomRepositoryMethods">http://www.aspnetboilerplate.com/Pages/ ... oryMethods</a>). In this method, you can get dbcontext using Context property.
  • User Avatar
    0
    andis created

    Create, SaveChanges and GetId() step is exactly what i tested before submit this ticket. But it seems EF has cached the created object, that's why in solution suggest me to detach it first and find it again..

    Ok, I'll try your CustomRepository Solution

  • User Avatar
    0
    andis created

    When resolving dependency, is IRepository<Entity, IdType) also inherit from EfRepositoryBase? if yes, then i can just cast it to this Type and get Context property instead re-implementing whole class

  • User Avatar
    0
    hikalkan created
    Support Team

    Yes, from v0.9.3.0 (which is released yesterday), you can do this for any EF based repository:

    repository.GetDbContext();

    This will give you a DbContext instance. You can cast it to your DbContext if you like.

    Upgrade to Abp.* 0.9.3 and add "using Abp.EntityFramework.Repositories;" to your code. Then GetDbContext extension method will be available.