我一直在我的 POCO 中使用 Money 的自定义类型,并尝试将其插入我的数据库,但它被 Entity Framework 隐式丢弃了。
这是我简化的代码;
我的类型;
public struct Money
{
private static decimal _value;
public Money(Decimal value)
{
_value = value;
}
public static implicit operator Money(Decimal value)
{
return new Money(value);
}
public static implicit operator decimal(Money value)
{
return _value;
}
}
我的对象;
public class MyObject
{
[Key]
public int Id { get; set; }
public Money MyMoney { get; set; }
}
我的背景;
public class Data : DbContext
{
public Data()
: base("Data Source=.;Database=MyTest;Integrated Security=True")
{}
public DbSet<MyObject> MyObject { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyObject>()
.Property(p => p.MyMoney).HasColumnName("MyMoney");
}
}
当我使用此代码时,出现以下错误。
The property 'MyMoney' is not a declared property on type 'MyObject'. Verify that the property has not been explicitly excluded from the model by using the Ignore method or NotMappedAttribute data annotation. Make sure that it is a valid primitive property.
我想问题出在最后一句话.... 那么,什么是有效的原始属性?有没有其他方法可以解决这个问题?
请您参考如下方法:
您可以通过显式映射 decimal 属性并仅向调用者公开 Money 属性来实现它:
public class MyObject
{
[Key]
public int Id { get; set; }
protected decimal MyMoney { get; set; }
public Money MyMoneyStruct
{
get { return (Money)this.MyMoney; }
set { this.MyMoney = (decimal)value; }
}
}
