EF 4.1-如何为日期时间列添加默认插入 [英] EF 4.1 - How to add a default on insertion for datetime column

查看:146
本文介绍了EF 4.1-如何为日期时间列添加默认插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用EF 4.1如何向基础表添加默认值?在这种特殊情况下,我如何在每次向数据库中插入新记录时都将datetime列设置为与getdate等效,而不必在代码中进行设置.

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.

预先感谢

推荐答案

@elkdanger提出的解决方案是可行的方法,但是即使您使用代码优先方法,也不必创建局部类-您可以放置​​初始化直接到您的实体.

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.

最后一个选项是覆盖派生的DbContext中的SaveChanges并手动设置属性.像这样:

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.

这篇关于EF 4.1-如何为日期时间列添加默认插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆