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

后端 未结 7 2039

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:39

    I know this topic is going on for a while and I walked into some kind of the same issue. So far I couldn't find a solution for me that keeps the whole thing together at one place so the code is still readable.

    At creation of an user I want to have some fields set by the object itself via private setters, e.g. a GUID and Creation Date and not 'polluting' the constructor.

    My User class:

    public class User
    {
        public static User Create(Action init)
        {
            var user = new User();
            user.Guid = Guid.NewGuid();
            user.Since = DateTime.Now;
            init(user);
            return user;
        }
    
        public int UserID { get; set; }
    
        public virtual ICollection Roles { get; set; }
        public virtual ICollection Widgets { get; set; }
    
        [StringLength(50), Required]
        public string Name { get; set; }
        [EmailAddress, Required]
        public string Email { get; set; }
        [StringLength(255), Required]
        public string Password { get; set; }
        [StringLength(16), Required]
        public string Salt { get; set; }
    
        public DateTime Since { get; private set; }
        public Guid Guid { get; private set; }
    }
    

    Calling code:

    context.Users.Add(User.Create(c=>
    {
        c.Name = "Name";
        c.Email = "some@one.com";
        c.Salt = salt;
        c.Password = "mypass";
        c.Roles = new List { adminRole, userRole };
    }));
    

提交回复
热议问题