How to map column and entity propery of different datatypes in entity framework code first

Specify numeric type for column

Property(x => x.Id).HasColumnName("Customer_id").HasColumnType("numeric");

When generating database, it will create numeric column with precision 18,0. But when you are mapping to existing database, it will work fine with 5,0 numeric column.


The simplest solution is to use another field that will be mapped to the database field, and the ID property will read/write to this field. Something like this:

public class Customer : IEntity
{
   public decimal CustomerID {get; set;}

   [NotMapped]
   public int Id 
   { 
      get { return (int)CustomerID; }
      set { CustomerID = (int)value; } 
   }

   public string FirstName { get; set; }

   public string LastName { get; set; }
}

Map this new field to the database field, using

this.Property(x => x.CustomerID).HasColumnName("Customer_id");

and the EF will use the customer id field, and your code could happily use the integer id field.