このコードファーストのアプローチを試していますが、System.Decimal型のプロパティがdecimal(18、0)型のSQL列にマップされていることがわかりました。
データベース列の精度を設定するにはどうすればよいですか?
このコードファーストのアプローチを試していますが、System.Decimal型のプロパティがdecimal(18、0)型のSQL列にマップされていることがわかりました。
データベース列の精度を設定するにはどうすればよいですか?
Dave VandenEyndeからの回答は現在古くなっています。2つの重要な変更があります。EF4.1以降、ModelBuilderクラスはDbModelBuilderになり、次のシグネチャを持つDecimalPropertyConfiguration.HasPrecisionメソッドがあります。
public DecimalPropertyConfiguration HasPrecision(
byte precision,
byte scale )
ここで、precisionは、小数点がどこにあるかに関係なく、dbが格納する桁の総数であり、scaleは、格納する小数点以下の桁数です。
したがって、示されているようにプロパティを繰り返す必要はありませんが、から呼び出すことができます
public class EFDbContext : DbContext
{
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);
base.OnModelCreating(modelBuilder);
}
}
EF6ですべての精度を設定する場合は、 :で使用されてdecimals
いるデフォルトの規則を置き換えることができます。DecimalPropertyConvention
DbModelBuilder
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(38, 18));
}
DecimalPropertyConvention
EF6のデフォルトでは、decimal
プロパティがdecimal(18,2)
列にマップされます。
個々のプロパティに指定された精度のみを持たせたい場合は、エンティティのプロパティの精度をDbModelBuilder
:で設定できます。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().Property(e => e.Value).HasPrecision(38, 18);
}
EntityTypeConfiguration<>
または、精度を指定するエンティティにを追加します。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new MyEntityConfiguration());
}
internal class MyEntityConfiguration : EntityTypeConfiguration<MyEntity>
{
internal MyEntityConfiguration()
{
this.Property(e => e.Value).HasPrecision(38, 18);
}
}
このためのカスタム属性を作成するのに楽しい時間を過ごしました:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
public DecimalPrecisionAttribute(byte precision, byte scale)
{
Precision = precision;
Scale = scale;
}
public byte Precision { get; set; }
public byte Scale { get; set; }
}
このように使う
[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }
魔法はモデルの作成時に発生します
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
select t)
{
foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
{
var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
ParameterExpression param = ParameterExpression.Parameter(classType, "c");
Expression property = Expression.Property(param, propAttr.prop.Name);
LambdaExpression lambdaExpression = Expression.Lambda(property, true,
new ParameterExpression[]
{param});
DecimalPropertyConfiguration decimalConfig;
if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
else
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
最初の部分は、モデル内のすべてのクラスを取得することです(私のカスタム属性はそのアセンブリで定義されているため、モデルでアセンブリを取得するためにそれを使用しました)
2番目のforeachは、カスタム属性と属性自体を使用してそのクラスのすべてのプロパティを取得するため、精度とスケールのデータを取得できます
その後、私は電話する必要があります
modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECISION,SCALE);
したがって、リフレクションによってmodelBuilder.Entity()を呼び出し、それをentityConfig変数に格納してから、「c=>c.PROPERTY_NAME」ラムダ式を作成します。
その後、小数がnull許容の場合、私は
Property(Expression<Func<TStructuralType, decimal?>> propertyExpression)
メソッド(私はこれを配列内の位置で呼びます、それは私が知っている理想ではありません、どんな助けでも大いに感謝されます)
null許容型でない場合は、
Property(Expression<Func<TStructuralType, decimal>> propertyExpression)
方法。
DecimalPropertyConfigurationを使用して、HasPrecisionメソッドを呼び出します。
DecimalPrecisonAttribute
from KinSlayerUYを使用すると、EF6で、属性を持つ個々のプロパティを処理する規則を作成できます(この回答で、すべての10進プロパティに影響するDecimalPropertyConvention
ようなものを設定するのとは対照的です)。
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
public DecimalPrecisionAttribute(byte precision, byte scale)
{
Precision = precision;
Scale = scale;
}
public byte Precision { get; set; }
public byte Scale { get; set; }
}
public class DecimalPrecisionAttributeConvention
: PrimitivePropertyAttributeConfigurationConvention<DecimalPrecisionAttribute>
{
public override void Apply(ConventionPrimitivePropertyConfiguration configuration, DecimalPrecisionAttribute attribute)
{
if (attribute.Precision < 1 || attribute.Precision > 38)
{
throw new InvalidOperationException("Precision must be between 1 and 38.");
}
if (attribute.Scale > attribute.Precision)
{
throw new InvalidOperationException("Scale must be between 0 and the Precision value.");
}
configuration.HasPrecision(attribute.Precision, attribute.Scale);
}
}
次に、あなたのDbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new DecimalPrecisionAttributeConvention());
}
どうやら、DbContext.OnModelCreating()メソッドをオーバーライドして、次のように精度を構成できます。
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Property(product => product.Price).Precision = 10;
modelBuilder.Entity<Product>().Property(product => product.Price).Scale = 2;
}
しかし、これは、価格に関連するすべてのプロパティで実行する必要がある場合、かなり退屈なコードであるため、私はこれを思いつきました。
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
var properties = new[]
{
modelBuilder.Entity<Product>().Property(product => product.Price),
modelBuilder.Entity<Order>().Property(order => order.OrderTotal),
modelBuilder.Entity<OrderDetail>().Property(detail => detail.Total),
modelBuilder.Entity<Option>().Property(option => option.Price)
};
properties.ToList().ForEach(property =>
{
property.Precision = 10;
property.Scale = 2;
});
base.OnModelCreating(modelBuilder);
}
基本実装は何もしませんが、メソッドをオーバーライドするときに基本メソッドを呼び出すことをお勧めします。
更新:この記事も非常に役に立ちました。
[Column(TypeName = "decimal(18,2)")]
これは、ここで説明するように、EFコアコードの最初の移行で機能します。
Entity Framework Ver 6(Alpha、rc1)には、カスタム規則と呼ばれるものがあります。小数精度を設定するには:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}
参照:
このコード行は、同じことを達成するためのより簡単な方法である可能性があります。
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
this.Property(m => m.Price).HasPrecision(10, 2);
}
}
-EFCOREの場合-System.ComponentModel.DataAnnotations を使用します。
使用 [Column
(TypeName
= "decimal
(精度、スケール)")]
精度=使用された文字の総数
スケール=ドットの後の総数。(混乱しやすい)
例:
public class Blog
{
public int BlogId { get; set; }
[Column(TypeName = "varchar(200)")]
public string Url { get; set; }
[Column(TypeName = "decimal(5, 2)")]
public decimal Rating { get; set; }
}
詳細はこちら:https ://docs.microsoft.com/en-us/ef/core/modeling/relational/data-types
.NET EF Core 6以降では、Precision属性を使用できます。
[Precision(18, 2)]
public decimal Price { get; set; }
using
EF Core 6をインストールし、次の行を実行する必要があることを確認してください
using Microsoft.EntityFrameworkCore;
次のように、OnModelCreating関数のContextクラスの規則を使用してこれを行うようにEFにいつでも指示できます。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// <... other configurations ...>
// modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
// modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// Configure Decimal to always have a precision of 18 and a scale of 4
modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
modelBuilder.Conventions.Add(new DecimalPropertyConvention(18, 4));
base.OnModelCreating(modelBuilder);
}
これは、Code First EF fyiにのみ適用され、dbにマップされたすべての10進タイプに適用されます。
EF6では
modelBuilder.Properties()
.Where(x => x.GetCustomAttributes(false).OfType<DecimalPrecisionAttribute>().Any())
.Configure(c => {
var attr = (DecimalPrecisionAttribute)c.ClrPropertyInfo.GetCustomAttributes(typeof (DecimalPrecisionAttribute), true).FirstOrDefault();
c.HasPrecision(attr.Precision, attr.Scale);
});
使用する
System.ComponentModel.DataAnnotations;
その属性をモデルに単純に入れることができます:
[DataType("decimal(18,5)")]
詳細については、MSDN(エンティティデータモデルのファセット)を参照してください。 http://msdn.microsoft.com/en-us/library/ee382834.aspx 完全に推奨されます。
EntityFrameworkCore 3.1.3の実際:
OnModelCreatingのいくつかの解決策:
var fixDecimalDatas = new List<Tuple<Type, Type, string>>();
foreach (var entityType in builder.Model.GetEntityTypes())
{
foreach (var property in entityType.GetProperties())
{
if (Type.GetTypeCode(property.ClrType) == TypeCode.Decimal)
{
fixDecimalDatas.Add(new Tuple<Type, Type, string>(entityType.ClrType, property.ClrType, property.GetColumnName()));
}
}
}
foreach (var item in fixDecimalDatas)
{
builder.Entity(item.Item1).Property(item.Item2, item.Item3).HasColumnType("decimal(18,4)");
}
//custom decimal nullable:
builder.Entity<SomePerfectEntity>().Property(x => x.IsBeautiful).HasColumnType("decimal(18,4)");
KinSlayerUYのカスタム属性はうまく機能しましたが、ComplexTypesに問題がありました。それらは属性コードのエンティティとしてマップされていたため、ComplexTypeとしてマップできませんでした。
したがって、これを可能にするためにコードを拡張しました。
public static void OnModelCreating(DbModelBuilder modelBuilder)
{
foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
where t.IsClass && t.Namespace == "FA.f1rstval.Data"
select t)
{
foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
{
ParameterExpression param = ParameterExpression.Parameter(classType, "c");
Expression property = Expression.Property(param, propAttr.prop.Name);
LambdaExpression lambdaExpression = Expression.Lambda(property, true,
new ParameterExpression[] { param });
DecimalPropertyConfiguration decimalConfig;
int MethodNum;
if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
MethodNum = 7;
}
else
{
MethodNum = 6;
}
//check if complextype
if (classType.GetCustomAttribute<ComplexTypeAttribute>() != null)
{
var complexConfig = modelBuilder.GetType().GetMethod("ComplexType").MakeGenericMethod(classType).Invoke(modelBuilder, null);
MethodInfo methodInfo = complexConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
decimalConfig = methodInfo.Invoke(complexConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
else
{
var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[MethodNum];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
@ Mark007、DbContextのDbSet<>プロパティに乗るようにタイプ選択基準を変更しました。特定の名前空間にモデル定義の一部であってはならないクラスがある場合や、エンティティではないクラスがある場合があるため、これはより安全だと思います。または、エンティティを別々の名前空間または別々のアセンブリに配置して、1つのコンテキストにまとめることもできます。
また、可能性は低いですが、メソッド定義の順序に依存するのは安全ではないと思いますので、パラメーターリストでそれらを引き出す方が良いでしょう。(.GetTypeMethods()は、新しいTypeInfoパラダイムで動作するように構築した拡張メソッドであり、メソッドを探すときにクラス階層をフラット化できます)。
OnModelCreatingはこのメソッドに委任することに注意してください。
private void OnModelCreatingSetDecimalPrecisionFromAttribute(DbModelBuilder modelBuilder)
{
foreach (var iSetProp in this.GetType().GetTypeProperties(true))
{
if (iSetProp.PropertyType.IsGenericType
&& (iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>) || iSetProp.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)))
{
var entityType = iSetProp.PropertyType.GetGenericArguments()[0];
foreach (var propAttr in entityType
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) })
.Where(propAttr => propAttr.attr != null))
{
var entityTypeConfigMethod = modelBuilder.GetType().GetTypeInfo().DeclaredMethods.First(m => m.Name == "Entity");
var entityTypeConfig = entityTypeConfigMethod.MakeGenericMethod(entityType).Invoke(modelBuilder, null);
var param = ParameterExpression.Parameter(entityType, "c");
var lambdaExpression = Expression.Lambda(Expression.Property(param, propAttr.prop.Name), true, new ParameterExpression[] { param });
var propertyConfigMethod =
entityTypeConfig.GetType()
.GetTypeMethods(true, false)
.First(m =>
{
if (m.Name != "Property")
return false;
var methodParams = m.GetParameters();
return methodParams.Length == 1 && methodParams[0].ParameterType == lambdaExpression.GetType();
}
);
var decimalConfig = propertyConfigMethod.Invoke(entityTypeConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
}
public static IEnumerable<MethodInfo> GetTypeMethods(this Type typeToQuery, bool flattenHierarchy, bool? staticMembers)
{
var typeInfo = typeToQuery.GetTypeInfo();
foreach (var iField in typeInfo.DeclaredMethods.Where(fi => staticMembers == null || fi.IsStatic == staticMembers))
yield return iField;
//this bit is just for StaticFields so we pass flag to flattenHierarchy and for the purpose of recursion, restrictStatic = false
if (flattenHierarchy == true)
{
var baseType = typeInfo.BaseType;
if ((baseType != null) && (baseType != typeof(object)))
{
foreach (var iField in baseType.GetTypeMethods(true, staticMembers))
yield return iField;
}
}
}