Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

c# - Entity framework: StoreGeneratedPattern="Computed" property

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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 the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...