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

c# entity-framework


I already have a POCO model class and a database table named which I am powerless to alter. Entity Framework 6 and the Fluent API are both used by me.

The CountryId of the model class is a "int." The CtryId, on the other hand, is a "tinyint" in the database table.

I tried using to set the type

modelBuilder.Entity<Event>().Property(e => e.CountryId).HasColumnName("CtryId").HasColumnType("tinyint");

the following error when using the OnModelCreating method:

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'.

How can I use Entity Framework Code First to translate a C# int to a SqlServer tinyint?

3/28/2014 1:15:40 PM

Accepted Answer

The short response is no.

As shown here, the mappings "align up."

The POCO's attribute should be "byte."

    public byte CountryId{ get; set; }

likewise the mapping

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

You must adhere to EF's rules.

The good news is that with a little magic, you can make anything work.

Because you don't want to violate the contract, you can find a solution.

public byte JustForMappingCtryId{ get; set; }

public int CountryId
        return Convert.ToInt32(this.JustForMappingCtryId);
        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 */      

likewise the mapping

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

Additionally, add a CountryId "ignore" attribute to the entity framework.

That's it. Although a workaround, it ought to satisfy your needs.

9/11/2019 10:59:50 PM

Popular Answer

In EF,int32 links toint the database. In this instancetinyint links tobyte throughout the.NET framework. You ought to alter yourCountryId as the kind ofbyte within the POCO concept.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow