0

I am using EF Core 5.0.1. I have the following model. I want to retrieve the navigation property after inserting data, but always return null. If I call "GetStockItemAsync" function it is returning with navigation values.

I tried, after a successful insert, to call "GetStockItemAsync" within "AddStockItemAsync" method, which is also returning null for navigations.

I have enabled lazy loading proxies in my asp.net core project.

public class StockType : MyDbObject
    {
        public StockType()
        {
            StockItems = new HashSet<StockItem>();
        }

        public int Id { get; set; }
        public string Type { get; set; }
        public string Description { get; set; }

        public virtual ICollection<StockItem> StockItems { get; set; }
    }
public class StockItem : MyDbObject
{
    public long Id { get; set; }
    public int TypeId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public virtual StockType Type { get; set; }
}
public interface IMyDbContext
{
        DbSet<StockType> StockTypes { get; set; }
        DbSet<StockItem> StockItems { get; set; }
        Task<TEntity> InsertAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : MyDbObject;
        void Create<TEntity>(TEntity entity) where TEntity : MyDbObject;
        Task<TEntity> GetFirstOrDefaultAsync<TEntity>(Expression<Func<TEntity, bool>> expression, CancellationToken cancellationToken = default) where TEntity : MyDbObject;
        Task CommitAsync(CancellationToken cancellationToken = default);
}

public class MyDbContext : IdentityDbContext<User, Role, Guid>, IMyDbContext
{
        public MyDbContext (DbContextOptions<MyDbContext> options) : base(options)
        { }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            //required mapping configuration added//
        }

        public DbSet<StockType> StockTypes { get; set; }
        public DbSet<StockItem> StockItems { get; set; }
        public async Task<TEntity> InsertAsync<TEntity>(TEntity entity, CancellationToken cancellationToken = default) where TEntity : MyDbObject
        {
            var savedEntity = await Set<TEntity>().AddAsync(entity, cancellationToken);
            return savedEntity.Entity;
        }
        public void Create<TEntity>(TEntity entity) where TEntity : MyDbObject
        {
            Set<TEntity>().Add(entity);
        }

        public async Task<TEntity> GetFirstOrDefaultAsync<TEntity>(Expression<Func<TEntity, bool>> expression, CancellationToken cancellationToken = default) where TEntity : MyDbObject
        {
            return await Set<TEntity>().Where(expression).FirstOrDefaultAsync(cancellationToken);
        }
        public async Task CommitAsync(CancellationToken cancellationToken = default)
        {
            await SaveChangesAsync(cancellationToken);
        }
}

public interface IStockItemServices
    {
        Task<StockItem> GetStockItemAsync(Expression<Func<StockItem, bool>> expression);
        Task AddStockItemAsync(StockItem stockItem);
    }
public class StockItemServices : IStockItemServices
    {
        private readonly IMyRestaurantContext _context;
        public StockItemServices(IMyDbContext context)
        {
            _context = context;
        }

        public async Task AddStockItemAsync(StockItem stockItem)
        {
            _context.Create(stockItem);
            await _context.CommitAsync();
        }
        
        public async Task<StockItem> GetStockItemAsync(Expression<Func<StockItem, bool>> expression) => await _context.GetFirstOrDefaultAsync(expression);
    }

Startup.cs settings:

services.AddDbContext<MyDbContext>(options =>
            {
                options.UseSqlServer(configuration.GetConnectionString("DbConnectionString"));
                options.UseLazyLoadingProxies(true);
            });
Mathavan
  • 1
  • 2
  • 5
  • 3
    You have to configure the relationships in the `OnModelCreating` using FluentAPI. More [here](https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration) – Ergis Jan 07 '21 at 06:48
  • After `DbSet.AddAsync`, you need call [DbContext.SaveChanges](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechanges?view=efcore-5.0). – vernou Jan 07 '21 at 07:44
  • Use synchronous context methods to add/update/delete unless you **need** async version. Use asynchronous method to save changes, to not block the calling thread. _"AddAsync() - This method is async only to allow special value generators, such as the one used by ValueGenerationStrategy to access the database asynchronously. For all other cases the non async method should be used."_ ~ [EF Core Docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.addasync?view=efcore-5.0) – Prolog Jan 10 '21 at 16:46
  • Read this [article on loading relating data in EF Core](https://learn.microsoft.com/ef/core/querying/related-data/). And as @Ergis already mentioned I see no relation configuration code for `StockItem` ==> `StockType`. If you are not sure what I'm talking about, read this [article on configuring relations in EF Core](https://learn.microsoft.com/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key). – Prolog Jan 10 '21 at 16:59
  • @Prolog This is my mapping https://gist.github.com/MathavanN/dec1abee181db7a34749890d4a82ff40 – Mathavan Jan 12 '21 at 02:20
  • @Prolog I got this issue when I insert new data. after successfully SaveChanges(), navigation properties showing null. But when I try to get that item using another get method, all the navigation properties are showing. I have updated to use synchronous context methods to add. Still, navigation property missing after insert. – Mathavan Jan 12 '21 at 02:30
  • I got the answer from this https://stackoverflow.com/questions/26610337/get-entity-navigation-properties-after-insert/26612605 – Mathavan Feb 18 '21 at 04:10
  • And maybe also this might help: https://stackoverflow.com/a/32414927/1016343 – Matt Apr 12 '21 at 14:35

0 Answers0