簡體   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