我有一个POCO模型类和一个现有的数据库表, neither of which I am able to change 我正在使用Entity Framework 6和Fluent API .
模型类的CountryId为'int' . 但是,在数据库表中,CtryId是'tinyint' .
我尝试使用设置类型
modelBuilder.Entity<Event>().Property(e => e.CountryId).HasColumnName("CtryId").HasColumnType("tinyint");
在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'.
如何使用Entity Framework Code First将C#int映射到SqlServer tinyint?
3 回答
你不能 .
映射“排列”如下 .
POCO上的属性应为“byte” .
和映射:
既然你不想违反 Contract .....你可以做一个解决方法 .
和映射:
并在CountryId上放置一个实体框架“ignore”属性
在EF中,
int32
映射到数据库中的int
. 在这种情况下,tinyint
映射到.NET框架中的byte
. 您应该将CountryId
更改为POCO模型中的byte
类型 .您可以使用
byte
列创建一个新的POCO类,并使用它而不是旧的POCO类 .您可以使用AutoMapper复制较高层中使用的旧POCO类与存储库层中使用的新POCO类之间的值以进行存储 .