首页 > 解决方案 > 仅存储年份和月份的实体框架类型

问题描述

我想在实体上保存生产年份和月份。我不想保存月份的时间和日期。

我可以想出多种解决方案,目前最好的两个是:

public class Product
{
    private DateTime _productionMonth;

    public DateTime ProductionMonth
    {
        get => _productionMonth;
        set => _productionMonth = new DateTime(value.Year, value.Month, 1);
    }
}

或者

public class Product
{
    public int Year { get; set; }
    public int Month { get; set; }
}

但我不觉得任何解决方案都是完美的解决方案......

有没有更好的解决方案?也许是一个属性DateTime

标签: c#entity-frameworktsqldatetime

解决方案


您可以使用 YYYYMM 格式将其存储为单个整数。实体可以公开未映射 ( [NotMapped]) 辅助方法以覆盖 to/fromDateTime和/或 ValueTuple,(year int, month int)尽管您需要使用单个映射值从 EF 查询。YYYYMM 是可排序的,因此您可以有效地查询范围。


推荐阅读