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

后端 未结 5 1261
北恋
北恋 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:56

    In .Net Core you can also use System.ComponentModel.DataAnnotations.Schema.ColumnAttribute to annotate the property with the underlying column type, e.g.,

        [Column(TypeName = "numeric(5, 0), not null")]
        public int Id { get; set; }
    

    Or if the column is nullable:

        [Column(TypeName = "numeric(5, 0), null")]
        public int? Id { get; set; }
    

    I prefer this to the accepted answer by @Sergey Berezovskiy, as you make the annotation actually on the model, not in elsewhere (in the DbContext).

    The ColumnAttribute can also be used to map a property to a column with a different name, e.g.,

        [Column("Identifier", TypeName = "numeric(5, 0), not null")]
        public int Id { get; set; }
    

    The ColumnAttribute may also work in the .Net Framework - I have not tested it.

提交回复
热议问题