Property StoreGeneratedPattern="Computed" in Entity Framework c# entity-framework sql-server-2005


I possessDateTime property. I need the default value of this attribute to beDateTime.Now . Later, I learned that you may specify an attribute.StoreGeneratedPattern="Computed" and change it to(getdate()) in SQL. This strategy is effective. But using code, I am unable to alter this attribute. This property has to be changed sometimes to any DateTime value. My modifications, however, are not stored.

7/16/2013 6:52:12 PM

Accepted Answer

By setting this property's value to computed, you are informing EF that the value was manually entered. How could you? For the benefit of calculated columns, which are by nature not stored back to the database, this feature is present.

The "Default Value" attribute of EF may, sadly, only be set to values that are known at build time.DateTime.Now

This website offers a respectable workaround:

Changing a DateTime Property's default value to DateTime. presently inside the System. Attribute for ComponentModel's Default Value

You'll be able to manage theSavingChanges only occurs when you call an event on your context and put default values there.SaveChanges() not at the time the thing is made.

    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)

        foreach(Invoice I in Invoices)
            if (I.EntityState == System.Data.EntityState.Added) {
                //set default values
            } else {
                //??  whatever
5/23/2017 12:30:33 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow