实体框架:StoreGeneratedPattern =“计算”属性 [英] Entity framework: StoreGeneratedPattern="Computed" property

查看:79
本文介绍了实体框架:StoreGeneratedPattern =“计算”属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DateTime 属性。我需要此属性的默认值为 DateTime.Now 。然后我发现您可以指定一个属性 StoreGeneratedPattern =Computed并将其设置为(getdate())在SQL中。这成功了但是我不能在代码中更改此属性。有时我需要将此属性更改为任何DateTime值。但是我的更改不会被保存。

I have a DateTime property. I need this property's default value to be DateTime.Now. And then I found out that you can specify an attribute StoreGeneratedPattern="Computed" and set it to (getdate()) in SQL. This works successfully. But I can't change this property in code. Sometimes I need to change this property to any DateTime value. But my changes are not saved.

推荐答案

将此属性设置为Computed,告诉EF您不能直接设置值。你怎么能?此属性存在为计算列,根据定义不保存回数据库。

Setting this property to Computed is telling EF that you cannot set the value directly. How could you? This property exists for the sake of computed columns, which by definition are not saved back to the database.

不幸的是,EF的默认值属性只能设置为值在编译时已知,所以不是 DateTime.Now

Unfortunately, EF's "Default Value" property can only be set to values known at compile-time, and so not DateTime.Now

此链接提供了一个体面的解决方法:

This link provides a decent workaround:

将DateTime属性的默认值设置为DateTime.Now System.ComponentModel默认值Attrbute

您还可以处理上下文中的 SavingChanges 事件,并在其中添加默认值,但只有当您实际调用 SaveChanges(),而不是当对象创建时。

You can also handle the SavingChanges event on your context, and add default values there, but that only happens when you actually call SaveChanges(), not when the object is created.

    partial void OnContextCreated() {
        this.SavingChanges += new EventHandler(AccrualTrackingEntities_SavingChanges);
    }

    void AccrualTrackingEntities_SavingChanges(object sender, EventArgs e) {
        List<Invoice> Invoices = this.ObjectStateManager
            .GetObjectStateEntries(System.Data.EntityState.Added | System.Data.EntityState.Modified)
            .Select(entry => entry.Entity)
            .OfType<Invoice>().ToList();

        foreach(Invoice I in Invoices)
            if (I.EntityState == System.Data.EntityState.Added) {
                //set default values
            } else {
                //??  whatever
            }
    }

这篇关于实体框架:StoreGeneratedPattern =“计算”属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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