How to set default value for POCO's in EF CF?

后端 未结 7 1993

In Entity Framework Code First approach, how do you set a default value for a property in the POCO\'s EntityConfiguration class?

public class Person
{
    pu         


        
相关标签:
7条回答
  • 2020-11-29 07:55

    I'm not sure as of what version of EF this becomes available, but as of version 5 for sure you can handle this. Just set a default value of GetDate() on the column in SQL, either in TSQL or the designer, then setup your EF classes as follows:

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreatedOn { get; set; }
    }
    
    public class PersonConfiguration : EntityConfiguration<Person>
    {
        public PersonConfiguration()
        {
            Property(p => p.Id).IsIdentity();
            Property(p => p.Name).HasMaxLength(100);
    
            this.Property(p => p.CreatedOn ).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed);
        }
    }
    

    Note that you don't need to make the database column nullable, or the POCO property.

    0 讨论(0)
提交回复
热议问题