繁体   English   中英

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

[英]How do I map a C# int to a SqlServer tinyint using Entity Framework Code First?

我有一个 POCO 模型类和一个现有的 DB 表,我无法更改这两个表,我使用的是 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'.

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

简短的回答:你不能。

映射“排列”如下。

POCO 上的属性应该是“字节”。

    public byte CountryId{ get; set; }

和映射:

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

你必须遵守 EF 的规则。

然而,好消息是你可以用一点魔法让它工作。

既然你不想破坏合同......你可以做一个解决方法。

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 */      
    }
}

和映射:

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

并在 CountryId 上放置一个实体框架“忽略”属性。 (以上视为 [NotMapped]) .. 或使用 Fluent 方式指定忽略(上面的代码中未显示)但下面是面包屑:

 modelBuilder.Entity<MyEntity>().Ignore(c => c.MyPocoProperty);

有你去。 这是一种解决方法,但应该适合您的需要。

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

您可以创建一个带有byte列的新 POCO 类并使用它代替旧的 POCO 类。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM