如何使用Entity Framework Code First将C#int映射到SqlServer tinyint?

我有一个POCO模型类和一个现有的数据库表, 我都无法改变,我正在使用Entity Framework 6和Fluent API。

模型类的CountryId为’int’。 但是,在数据库表中,CtryId是’tinyint’。

我尝试使用设置类型

modelBuilder.Entity().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?

你不能。

映射“排列”如下。

POCO上的属性应为“byte”。

  public byte CountryId{ get; set; } 

和映射:

  this.Property(t => t.CountryId).HasColumnName("CtryId"); 

既然你不想违反合同…..你可以做一个解决方法。

 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上放置一个entity framework“ignore”属性

在EF中, int32映射到db中的int 。 在这种情况下, tinyint映射到.NET框架中的byte 。 您应该将CountryId更改为POCO模型中的byte类型。

您可以使用byte列创建一个新的POCO类,并使用它而不是旧的POCO类。

您可以使用AutoMapper复制较高层中使用的旧POCO类与存储库层中使用的新POCO类之间的值以进行存储。