I would like to how to load/fetch the current database values for an entity ("force reload from database") with Entity Framework Core. My property looks like the following:
[Column(TypeName = "decimal(16, 2)")]
public decimal Fee { get; set; }
If the Fee is saved with a higher precision than the one specified in the Column Attribute e.g. 1,2888
the Database round it to two decimal placed but the entity I save does not get Updated.
So I tried to reload the values from the database to show the "correct current" values in this UI but neither of the following worked:
// removed from tracked entities and fetch from db
dbContext.Entry(entity).State = EntityState.Detached;
dbContext.Find(...);
// call reload
dbContext.Entry(entity).Reload();
Expected the value to be 1,29
after the refresh/reload but it always stays 1,2888
. I have looked up the value in the database and it was 1,29
and also the next request would return 1,29
but I did not manage to return the correct value in the same request.
Is there a way to "force refresh" an Entity from the database?
--- Edit ---
The Problem was that I had an Entity with Navigation Properties and the decimal was on the navigation property which was not reloaded when calling .Reload() on the entity itself.
Code
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1
{
public class Entity
{
public long Id { get; set; }
public Fee Fee { get; set; }
}
public class Fee
{
public long Id { get; set; }
[Column(TypeName = "decimal(16, 2)")]
public decimal Value { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Entity> Entities { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(@"connectionString");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
public class Program
{
public static void Main()
{
AsyncMethod().GetAwaiter().GetResult();
}
private static async Task AsyncMethod()
{
using (var context = new MyContext())
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
using (var context = new MyContext())
{
var entity = new Entity {Fee = new Fee {Value = 12.3456789m}};
context.Add(entity);
await context.SaveChangesAsync();
Console.WriteLine($"Fee value after SaveChanges() {entity.Fee.Value}");
await context.Entry(entity).ReloadAsync();
Console.WriteLine($"Fee value after Reload() {entity.Fee.Value}");
}
using (var context = new MyContext())
{
var entity = await context.Entities.OrderByDescending(x => x.Id).Include(x => x.Fee).FirstAsync();
Console.WriteLine($"Fee value after Disposing and Recreating Context {entity.Fee.Value}");
}
}
}
}
Output:
Fee value after SaveChanges() 12,3456789
Fee value after Reload() 12,3456789
Fee value after Disposing and Recreating Context 12,35