46

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
{
    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);

        //set default value for CreatedOn ?
    }
}
2
  • 2
    In case anyone wonder. I end up using 'Repository Pattern' (stackoverflow.com/questions/3175/…), setting the default values during INSERT. It's a nice separation, since I'm thinking of moving away from EF in the future.
    – Andy
    Apr 4, 2013 at 16:01
  • +1 for "moving away from EF in the future". Wasted a lot of time I could've just coded SQL for my current app! But what are you going to use? NHibernate, is it better?
    – Lzh
    Mar 11, 2014 at 2:46

7 Answers 7

24

With the release of Entity Framework 4.3 you can do this through Migrations.

EF 4.3 Code First Migrations Walkthrough

So using your example it would be something like:

public partial class AddPersonClass : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "People",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(maxLength: 100),
                    CreatedOn = c.DateTime(nullable: false, defaultValue: DateTime.UtcNow)
                })
            .PrimaryKey(t => t.Id);
    }

    public overide void Down()
    {
        // Commands for when Migration is brought down
    }
}
2
  • 1
    Can you use AlterColumn to successfully modify default values without dropping and recreating the column or table?
    – Benjamin
    Jun 15, 2012 at 15:34
  • 4
    Is there a way to do this via extending EntityTypeConfiguration? For example, anything with a Guid always defaults to newsequentialid()?
    – drzaus
    Aug 27, 2012 at 21:36
15

You can set the default values via the constructor for the class. Here is a class I have in my current project, using MVC3 and Entity Framework 4.1:

namespace MyProj.Models
{
using System;
using System.Collections.Generic;

public partial class Task
{
    public Task()
    {
        this.HoursEstimated = 0;
        this.HoursUsed = 0;
        this.Status = "To Start";
    }

    public int ID { get; set; }
    public string Description { get; set; }
    public int AssignedUserID { get; set; }
    public int JobID { get; set; }
    public Nullable<decimal> HoursEstimated { get; set; }
    public Nullable<decimal> HoursUsed { get; set; }
    public Nullable<System.DateTime> DateStart { get; set; }
    public Nullable<System.DateTime> DateDue { get; set; }
    public string Status { get; set; }

    public virtual Job Job { get; set; }
    public virtual User AssignedUser { get; set; }
}
}
1
  • 11
    What if the database stored value for HoursUsed is 5.0? Will the constructor overwrite the database value? Or will it construct first and then replace the default 0 with the actual value?
    – Benjamin
    Jun 15, 2012 at 15:36
7

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<User> 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<Role> Roles { get; set; }
    public virtual ICollection<Widget> 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 = "[email protected]";
    c.Salt = salt;
    c.Password = "mypass";
    c.Roles = new List<Role> { adminRole, userRole };
}));
0
4

Unfortunately you can't. http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/a091ccd6-0ba8-4d4f-8f5e-aafabeb258e4

5
  • 3
    Code-first is still a CTP. Please write a Connect report for this, if you haven't already. Jun 29, 2010 at 12:37
  • Actually I think it was an active design decision. Setting default values in database is a kind of step aside from code only approach. Jun 29, 2010 at 13:18
  • 2
    Well, I do expect the "Code Only" means everything is configure in the codes. Manually setting the default value in the db isn't a good idea, since I need the entity framework to create the database for me using the context.CreateDatabase() function, and I don't really want to maintain both codes and db script in the same time.
    – Andy
    Jun 30, 2010 at 2:27
  • 4
    You can consider default values to be the part of you Person class. When you set default values in the db you'll run into the following problem: those properties won't be initialized until you save your entity. It is a problem in DB First and Model First when you have generated POCOs. Jun 30, 2010 at 5:01
  • Do you think is a good idea adding default value in using the SavingChanges on the context?
    – GibboK
    Jul 4, 2012 at 7:13
3

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.

1
  • 2
    I think the point is to have EF set the default value when using Code First, and not have to get into SQL and set them yourself.
    – Kyle
    Apr 3, 2013 at 18:33
3

In the case where you want SQL Server to provide a default date the way you would accomplish this is, the important part is defaultValueSql: "GETDATE()" which will set the sql server default, not just evaluate to the time the script was run (i.e. DateTime.UtcNow)

   public partial class AddPersonClass : DbMigration
    {
    public override void Up()
    {
        CreateTable(
            "People",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(maxLength: 100),
                    CreatedOn = c.DateTime(nullable: false, defaultValueSql: "GETDATE()")
                })
            .PrimaryKey(t => t.Id);
    }

    public overide void Down()
    {
        // Commands for when Migration is brought down
    }
}
0

There is no other way but to use DB MIGRATIONS and to enable the migrations you must set your property like this

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]        
    public DateTime CreatedOn { get; set; }

And after that once your database is created you must follow the following steps to enable the migrations. Go to Program Manager console and Execute the following commands one by ones command

  • PM> Enable-Migrations
  • PM> Add-Migration AlterMyTable Here AlterMyTable can be any name. this will create a file under newly added Migrations folder in your solution currentTimestamp_AlterMyTable.cs -Now copy the following to the Up method of currentTimestamp_AlterMyTable.cs
  • AlterColumn("Person", "CreatedOn", n => n.DateTime(nullable: false, defaultValueSql: "SYSUTCDATETIME()")); And after that execute the last command in your Program Manager Console
  • PM> Update-Database And now if you see the Person table in your database and then navigate to the CreatedOn column it should be having the Default value as SYSUTCDATETIME() i.e. now if you try to insert some data to this table your database will automatically update this column CreatedOn for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.