EF Extras Project Update

Following the roadmap of my newest CodePlex project EF Code First Extras, I implemented support for default values as part of code-free migrations of SQL Server.

Default values is something that is necessary in order to support migrations.  If you are adding a new column to the table that does not allow nulls and you do not provide default value, your migration will fails.

I followed very simple code path in order to implement support.  I added default attribute to the project, and the users can simply add this new attribute to their classes in order to set default values in the database.  Attribute has two overloads – one that only takes default value as string, the other allows you to specify table and column name in addition to default value.  The reason for the second overload is the fact that some of the built-in configuration are not available to us, so if somebody changes table name via configuration, there is no way for the system to get to this information.  I do support however Table and Column attributes.

For example, let’s take a look at the following class:

    [Table("MyChair")]
   
public class Chair

    {
       
public int ChairID { get; set; }
       
public string Description { get; set
; }
 
        [
Column("ChairHeight"
)]
        [
Default("10"
)]
       
public decimal Height { get; set
; }
 
        [
Default("GetDate()"
)]
       
public DateTime DateAdded { get; set
; }
    }

 

As you see, I changed the table name, using MyChair instead of class name of Chair.  I also changed a column, using ChairHeight instead of property name of Height.  Default subsystem handles both use cases, applying the default value of 10 to the column.  As you also see, I support functions, such as GetDate(), so the newly added column DateAdded will be populated with current date/time value.  System if very flexible as you can see.  Of course, you can leave all name as is, and use much simpler code:

    public class Person
    {
       
public int PersonID { get; set; }
       
public string PersonName { get; set
; }
        [
Default("1"
)]
       
public bool IsActive { get; set
; }
        [
Default("People", "Salary", "1100"
)]
       
public decimal Salary { get; set
; }
    }

 

Above, the default for IsActive column could not be simpler.  The default for Salary column explicitly specifies table and column name for the reason I described above.

Very easy and intuitive interface, if I have to say so myself.

Please let me know your questions.  As always I appreciate any suggestions.  You can download updated source code off CodePlex site.

Leave a Reply

Your email address will not be published. Required fields are marked *