如何使用实体框架代码首先将C#int映射到SqlServer tinyint? [英] How do I map a C# int to a SqlServer tinyint using Entity Framework Code First?
问题描述
我有一个POCO模型类和现有的数据库表,我都不能更改我正在使用Entity Framework 6和Fluent API。
I have a POCO model class and an existing DB table, neither of which I am able to change I am using Entity Framework 6 and the Fluent API.
模型类的CountryId为int。但是,在数据库表中,CtryId是一个'tinyint'。
The model class has a CountryId of 'int'. However, in the database table, the CtryId is a 'tinyint'.
我尝试使用
modelBuilder.Entity<Event>().Property(e => e.CountryId).HasColumnName("CtryId").HasColumnType("tinyint");
,但会出现以下错误:
error 2019: Member Mapping specified is not valid. The type 'Edm.Int32[Nullable=False,DefaultValue=]' of member 'CountryId' in type 'RA.Data.Event' is not compatible with 'SqlServer.tinyint[Nullable=False,DefaultValue=]' of member 'CtryId' in type 'CodeFirstDatabaseSchema.Event'.
如何使用实体框架代码首先将C#int映射到SqlServer tinyint?
How do I map a C# int to a SqlServer tinyint using Entity Framework Code First?
推荐答案
你不能。
映射排队如下。
POCO上的属性应为byte。
The property on the POCO should be "byte".
public byte CountryId{ get; set; }
和映射:
this.Property(t => t.CountryId).HasColumnName("CtryId");
既然你不想打破合同.....你可以做一个解决方法。
Since you don't want to break the contract..... you can do a workaround.
public byte JustForMappingCtryId{ get; set; }
[NotMapped]
public int CountryId
{
get
{
return Convert.ToInt32(this.JustForMappingCtryId);
}
set
{
if(value > 8 || value < 0 )
{
throw new ArgumentOutOfRangeException("Must be 8 or less, and greater or equal to zero.");
}
//this.JustForMappingCtryId = value; /* Do a conversion here */
}
}
和映射:
this.Property(t => t.JustForMappingCtryId).HasColumnName("CtryId");
在CountryId上放置一个实体框架ignore属性
And put an entity framework "ignore" attribute on CountryId
这篇关于如何使用实体框架代码首先将C#int映射到SqlServer tinyint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!