c# - 枚举正确存储在数据库中,但未在 C# 中正确反序列化为类型

标签 c# asp.net entity-framework enums ef-code-first

我有一个枚举:

public enum EnumSample{
    Setup = 1,
    Pending = 7
}

我有一个实体(我正在使用 EF)存储在数据库中,其 EnumSample 属性设置为 EnumSample.Pending。当我查询时,数据库将此值反射(reflect)为 7。但是,当我从 C#(使用 EF)中检索相同的实体时,我得到了不正确的类型映射(我得到了 Setup,而我应该得到 Pending)。所有 ID 都经过验证。屏幕截图如下。可能是什么原因造成的?

enter image description here

更新

重新启动应用程序得到了我所期望的 - 问题是 dbContext 的实例在请求之间停留。我可以 using var db = new AppContext 并且它工作正常。

我在我的 UnityContainer 上配置了以下内容:

   container.RegisterType<AppContext>(new ContainerControlledLifetimeManager());

我已经尝试了各种不同的生命周期管理器 - PerHttpRequestLifetimeManager 没有按照我看到的其他指导进行解析。

服务层方法示例:

   public class EventService : BaseService
   {

    public readonly AppContext _db;

    private readonly NotificationService _notificationService;

    public EventService(AppContext db, NotificationService notificationService)
    {
        _db = db;
        _notificationService = notificationService;
    }

我需要的行为是 EventServiceNotificationService 具有相同的 AppContext 实例,但是在请求之间,上下文被释放我得到了新的状态/新的实例。

最佳答案

PerThreadLifetimeManager 不保证每个请求将由不同的线程处理。默认情况下,Unity 没有每个请求生命周期管理器。您需要安装一个 nuget 包 Unity.MVC它有一个新的内置生命周期管理器:PerRequestLifetimeManager

@SB2055 参见this answer了解更多详情。

关于c# - 枚举正确存储在数据库中,但未在 C# 中正确反序列化为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528647/

相关文章:

c# - EF Code First 导航属性到同一个表

c# - 在 sql server 精简版上执行插入或更新(upsert)

ASP.NET 菜单和 CSS?

c# - "Input string was not in a correct format"没有有意义的堆栈跟踪的错误消息

java - 如何在 python 交易模型中创建运行时间条件?

c# - 使用 OpenCV/Emgu CV 进行焦点堆叠

c# - 如何使用 EF 在我的 asp.net core 3.1 MVC 应用程序中正确使用我的 SQLite db?

asp.net - Entity Framework ObjectContext 重用

c# - Entity Framework 不将对象保存到数据库

c# - 在多个管道服务器实例的情况下异步 NamedPipes