且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架:StoreGeneratedPattern ="已计算"属性

更新时间:2022-04-29 22:54:15

此属性设置为已计算告诉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.

不幸的是,英孚的默认值属性只能设置在编译时已知值,所以不能 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:

Setting一个DateTime属性的默认System.ComponentModel里面的默认值DateTime.Now值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
            }
    }