gpt4 book ai didi

c# - EF 4.1 使用自定义类型处理资金

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:48 26 4
gpt4 key购买 nike

我一直在我的 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; }
}
}

关于c# - EF 4.1 使用自定义类型处理资金,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5731054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com