EF Core 强制刷新数据库中的实体(强制从数据库获取值)

Edu*_*dub 6 sql-server precision decimal entity-framework-core .net-core

我想了解如何使用 Entity Framework Core 加载/获取实体的当前数据库值(“从数据库强制重新加载”)。我的属性如下所示:

[Column(TypeName = "decimal(16, 2)")]
public decimal Fee { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果费用以比列属性中指定的精度更高的精度保存,例如1,2888数据库将其四舍五入到两位小数,但我保存的实体不会得到更新。

因此,我尝试从数据库重新加载值以在此 UI 中显示“正确的当前”值,但以下两种方法均无效:

// removed from tracked entities and fetch from db
dbContext.Entry(entity).State = EntityState.Detached;
dbContext.Find(...);

// call reload
dbContext.Entry(entity).Reload();
Run Code Online (Sandbox Code Playgroud)

预期该值1,29在刷新/重新加载之后,但始终保持为1,2888。我已经在数据库中查找了该值,并且1,29下一个请求也会返回,1,29但我没有设法在同一个请求中返回正确的值。

有没有办法“强制刷新”数据库中的实体?

- - 编辑 - -

问题是我有一个带有导航属性的实体,小数点在导航属性上,在实体本身上调用 .Reload() 时没有重新加载。

代码

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}");
            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Fee value after SaveChanges() 12,3456789
Fee value after Reload() 12,3456789
Fee value after Disposing and Recreating Context 12,35
Run Code Online (Sandbox Code Playgroud)

Sim*_*ver 0

有限情况下的可能解决方案

AsNoTracking如果您只需要加载数据而不维护对象的整个上下文,有时可能是一个解决方案。https://learn.microsoft.com/en-us/ef/core/querying/tracking

例如,我刚刚遇到一个案例,我需要:

  • 加载单行
  • 启动hangfire任务(在自己的上下文中运行)
  • 原方法几秒后查看状态

通过使用,AsNoTracking我能够加载同一行两次,并且看不到任何缓存的内容。

var shipmentData = await context.Shipments.AsNoTracking().Single(s => s.ShipmentId == shipmentId);
Run Code Online (Sandbox Code Playgroud)

但是,如果您确实需要保存此行,则此方法可能会导致管理混乱或丢失更改的风险。