【问题标题】:Generate money type fields using code first EF CTP5使用代码优先 EF CTP5 生成货币类型字段
【发布时间】:2011-06-17 07:37:45
【问题描述】:

在这篇博文:EF4 Code First Control Unicode and Decimal Precision, Scale with AttributesDane Morgridge 使用属性来控制在您的数据库上创建不同类型。

...顺便说一句,我发现这个非常独特!!!

如何使用 EF CTP5 的代码优先 API 在生成的数据库中生成货币类型字段(如果可以从您的模型中使用约定或属性)?

对不起,我的英语不是我的主要语言。

提前致谢。

【问题讨论】:

  • 一般情况下(除非您使用现有的数据库模式),否则我会避免使用 SQL money 数据类型。您最好使用满足您的应用程序要求的具有特定精度和比例的小数
  • @Damien 很有趣...为什么会这样?
  • 相关,用于使用货币类型参数处理 EF 迁移:stackoverflow.com/questions/27696728/…

标签: entity-framework ef-code-first entity-framework-ctp5


【解决方案1】:

例如,考虑这个 Invoice 类:

public class Invoice
{
    public int InvoiceId { get; set; }                
    public decimal Amount { get; set; }
}

您可以使用流畅的 API 来做到这一点:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Invoice>()
                .Property(i => i.Amount)
                .HasColumnType("Money");
}

或者您可以使用数据注释来做到这一点:

public class Invoice
{
    public int InvoiceId { get; set; }                

    [Column(TypeName="Money")]
    public decimal Amount { get; set; }
}

【讨论】:

  • 不幸的是,EF 4.3(发行版)忽略了货币数据类型并改为创建十进制(18,0)定义(不支持 Column 属性和 HasColumnType 配置)。这绝对是一个错误。
  • EF 4.3.1 修复了 Column 属性未得到尊重的问题。使用 [Column(TypeName="Money")] 现在可以按预期工作。 blogs.msdn.com/b/adonet/archive/2012/02/29/…
【解决方案2】:
using System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive;

public class MoneyAttribute : Attribute { }

public class MoneyAttributeConvention : AttributeConfigurationConvention<PropertyInfo, DecimalPropertyConfiguration, MoneyAttribute> {
    public override void Apply(PropertyInfo memberInfo, DecimalPropertyConfiguration configuration, MoneyAttribute attribute) {
        configuration.ColumnType = "money";
    }
}

那你就这样用

[Money]
public decimal Value { get; set; }

【讨论】:

  • BinaryPropertyConfiguration 没有 HasColumnType 成员,我尝试了这种方法但没有用
  • 抱歉,正确的是configuration.ColumnType = "Money";。我只是编辑帖子。谢谢。
  • ahahaha,天哪,我很抱歉我的错.. 帖子已编辑,现在它应该可以工作了.. 谢谢好友
  • 我认为 EF 约定在发布之前已从 Code First 中删除?
  • 约定在 4.1 版中被删除。可能会在未来发布。
猜你喜欢
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2011-09-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多