2011-01-28 146 views
20

在此博客文章中:EF4 Code First Control Unicode and Decimal Precision, Scale with Attributes,Dane Morgridge使用属性来控制数据库上不同类型的创建。使用代码优先生成钱类型字段EF CTP5

...我发现这个非常独特的BTW!

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

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

在此先感谢。

+2

一般来说(除非你使用现有的数据库模式),我会避免使用SQL money数据类型。你最好使用具有特定精度和比例的小数以满足你的应用需求 – 2011-01-28 15:31:57

+2

@Damien有趣......为什么是这样? – 2011-06-20 20:20:49

+0

相关,使用钱类型参数与EF迁移工作:http://stackoverflow.com/questions/27696728/dbmigration-alterstoredprocedure-entity-framework-migration-how-to-represent – 2015-10-27 14:50:34

回答

40

例如,请考虑这样的发票类:

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; } 
} 
11
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; }