Ant*_*ony 7 c# entity-framework
我有一个POCO模型类和一个现有的数据库表,我无法改变我使用的实体框架6和Fluent API.
模型类的CountryId为'int'.但是,在数据库表中,CtryId是'tinyint'.
我尝试使用设置类型
modelBuilder.Entity<Event>().Property(e => e.CountryId).HasColumnName("CtryId").HasColumnType("tinyint");
Run Code Online (Sandbox Code Playgroud)
在OnModelCreating方法中,但得到以下错误:
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'.
Run Code Online (Sandbox Code Playgroud)
如何使用Entity Framework Code First将C#int映射到SqlServer tinyint?
你不能.
映射"排列"如下.
POCO上的属性应为"byte".
public byte CountryId{ get; set; }
Run Code Online (Sandbox Code Playgroud)
和映射:
this.Property(t => t.CountryId).HasColumnName("CtryId");
Run Code Online (Sandbox Code Playgroud)
既然你不想违反合同.....你可以做一个解决方法.
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; /* Uncomment this code.. to put back the setter... you'll have to do the conversion here (from the input int to the byte) of course..but the edited out code shows the intention */
}
}
Run Code Online (Sandbox Code Playgroud)
和映射:
this.Property(t => t.JustForMappingCtryId).HasColumnName("CtryId");
Run Code Online (Sandbox Code Playgroud)
并在CountryId上放置一个实体框架"ignore"属性
| 归档时间: |
|
| 查看次数: |
12195 次 |
| 最近记录: |