EF 4.1 - How to add a default on insertion for datetime column

后端 未结 6 654
野性不改
野性不改 2021-01-20 01:25

Using EF 4.1 how could I add a default value to the underlying table? In this particular case how could I set a datetime column to the equivalent of getdate every time I in

6条回答
  •  温柔的废话
    2021-01-20 02:00

    You can also modify your T4 template (.tt file) to add a partial method that you call from within the generated constructor. Then, you can create your own partial class and implement the partial method and set your default value.

    A snippet from the T4 template where the constructor is created, followed by the partial method. Note the last three lines:

    public <#=code.Escape(entity)#>()
    {
    <#
        foreach (var edmProperty in propertiesWithDefaultValues)
        {
    #>
        this.<#=code.Escape(edmProperty)#> = =code.CreateLiteral(edmProperty.DefaultValue)#>;
    <#
        }
    
        foreach (var navigationProperty in collectionNavigationProperties)
        {
    #>
        this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=code.Escape(navigationProperty.ToEndMember.GetEntityType())#>>();
    <#
        }
    
        foreach (var complexProperty in complexProperties)
        {
    #>
        this.<#=code.Escape(complexProperty)#> = new <#=code.Escape(complexProperty.TypeUsage)#>();
    <#
        }
    #>
    
        SetDefaultValues();
    }
    
    partial void SetDefaultValues();
    

    That will result in a generated entity having something like:

    public Foo()
    {
        // Properties set based on defaults in edmx
    
        SetDefaultValues();
    }
    
    partial void SetDefaultValues();
    

    Then, in your partial class, you can simply add something like:

    partial void SetDefaultValues()
    {
        this.SomeDate = DateTime.Today;
    }
    

提交回复
热议问题