C#实体框架未映射单元转换器

C#实体框架未映射单元转换器,c#,entity-framework,entity-framework-core,C#,Entity Framework,Entity Framework Core,我使用实体框架和SQLLite数据库来保存我的值。我有很多模型需要使用单位。每次更改某个值的单位时,该值都会被转换。我不想在每个单元的setter中写入每个转换 我的样本模型 所以事实上我想要这样的东西 单位价值类 public double? Value {get; set;} public System.Enum? BaseUnit { get; set; } private System.Enum? _Unit {get; set; } public System.Enum? Uni

我使用实体框架和SQLLite数据库来保存我的值。我有很多模型需要使用单位。每次更改某个值的单位时,该值都会被转换。我不想在每个单元的setter中写入每个转换

我的样本模型 所以事实上我想要这样的东西

单位价值类

public double? Value {get; set;}

public System.Enum? BaseUnit { get; set; }

private System.Enum? _Unit {get; set; }

public System.Enum? Unit  
{
   get => this._Unit ?? BaseUnit;
   set
   {
       double convertedValue;

       UnitsNet.UnitConverter.TryConvert(
            this.Value.Value,
            this._Unit,
            value,
            out double convertedValue);

       this.DiameterD = convertedValue;
       this._DiameterDUnit = value;
  }
在我的数据库模型中

public static UnitValue.Value DiameterD {get; set;}

[NotMapped]
public static UnitValue.BaseUnit { get => UnitsNet.Units.LengthUnit.Millimeter; }

[NotMapped]
public static UnitValue.Unit { get; set;} 
也许有一些最佳实践可以实现这一点。我也不想在数据库中创建新表。

您可以使用

//在DbContext类中
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
建模者
.实体()
.属性(x=>x.直径)
.哈斯转换(
v=>v.As(长度单位毫米),
v=>新长度(v,长度单位毫米);
}

我创建了一个库来帮助实现这一点:
然后您可以像这样重构代码:

模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
实体(生成器=>
{
builder.Property(x=>x.DiameterD).HasConversion(LengthUnit.mm);
builder.Property(x=>x.SpeedS).HasConversion(速度单位:公里小时);
});
}
public static UnitValue.Value DiameterD {get; set;}

[NotMapped]
public static UnitValue.BaseUnit { get => UnitsNet.Units.LengthUnit.Millimeter; }

[NotMapped]
public static UnitValue.Unit { get; set;}