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

半腔热情 提交于 2019-12-04 03:43:57

问题


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 insert a new record to the database, without having to set it in code.

Thanks in advance


回答1:


The solution proposed by @elkdanger is way to go but just if you use code-first approach you don't have to create partial class - you can place initialization directly to your entity.

Don't use database approach! It will not work because it would demand marking property as database generated (to be correctly repopulated after insert). Once you mark property database generated you can never change its value in the application.

The last option is overriding SaveChanges in your derived DbContext and setting the property manually. Something like:

public override int SaveChanges()
{
    var entities = ChangeTracker.Entries<YourEntityType>()
                                .Where(e => e.State == EntityState.Added)
                                .Select(e => e.Entity);
    var currentDate = DateTime.Now;
    foreach(var entity in entities)
    {
        entity.Date = currentDate;
    }

    return base.SaveChanges();
}

This approach can be better if there can be significant difference between creating an instance of the entity and saving the instanance.




回答2:


You could create a partial class for your entity, and inside the constructor set the date column to DateTime.Now. This way, every time you create an instance of your class, that field will be set to the current date "automatically".




回答3:


You could (and perhaps should) do it in the table itself using a trigger or a default value.




回答4:


Entity Framework itself has not a mechanism for it. You have to do it manually in the db or the code.




回答5:


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;
}



回答6:


Use [DatabaseGenerated(DatabaseGeneratedOption.Computed)] from System.ComponentModel.DataAnnotations.Schema;

if you have the default values configured on the database.



来源:https://stackoverflow.com/questions/6237619/ef-4-1-how-to-add-a-default-on-insertion-for-datetime-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!