Thursday, June 6, 2013

Entity Framework 5.0 - Set Nullable and NON Nullable columns using code first approach

To set column is not null using code first approach using entity framework set REQUIRED attribute to the property in class.
Example:-
    public class TemplateType
    { 
        [Key]
        public int TemplateTypeId { get; set; }
        [Column(TypeName="varchar")]
        [Required]
        [MaxLength(30)]
        public string TemplateName { get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedOn { get; set; }
    }
Inversely since Integer and Datetime cannot be null unless and until explicitly defined code first will generate schema for these types with NOT NULL in database.
To create a NULLABLE column in DB using Code First mark the property as NULLABLE(?).
Example:-
public int? ModifiedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
Hope this helps.

1 comment: