首页 文章

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

提问于
浏览
4

我有一个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 回答

  • 0

    你不能 .

    映射“排列”如下 .

    POCO上的属性应为“byte” .

    public byte CountryId{ get; set; }
    

    和映射:

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

    既然你不想违反 Contract .....你可以做一个解决方法 .

    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”属性

  • 6

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

  • -1

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

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

相关问题