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

后端 未结 5 1249
北恋
北恋 2020-12-10 14:33

I am using Entity Framework 5 - Code first.

I have a database that I am connecting to that already exists for some time now (I did not create it). There is a table

5条回答
  •  一向
    一向 (楼主)
    2020-12-10 14:52

    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.

提交回复
热议问题