且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用实体框架代码首先将C#int映射到SqlServer tinyint?

更新时间:2022-11-04 23:39:15

你不能。

映射排队如下。

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