简体   繁体   中英

how to tell Entity Framework to ignore database generates values for insert or update?

I'm new to Entity Framework in C# .

I'm having one computational column in my table table1 (example). I will calculate the computational column value based on the other columns value. I don't want Entity Framework to include the computational column while performing insert/update operations. How can I make the EF to avoid that particular column. But I want to set the value for that particular column manually.

I searched for the same but i couldn't able to get the answer for my question. Kindly help me and thanks in advance.

You can use the NotMapped Annotation

Code first convention dictates that every property that is of a supported data type is represented in the database. That property can be created dynamically and does not need to be stored. You can mark any properties that do not map to the database with the NotMapped annotation.

[NotMapped]
public string Something
{
    get
    {
        return _something;
    }
    set
    {
        _something = value
    }
}

Update : this is will not map to the dB, so is probably not what you are looking for


Just to make this a more complete the DatabaseGenerated Annotation, are the droids you are looking for

An important database features is the ability to have computed properties. If you're mapping your Code First classes to tables that contain computed columns, you don't want Entity Framework to try to update those columns. But you do want EF to return those values from the database after you've inserted or updated data. You can use the DatabaseGenerated annotation to flag those properties in your class along with the Computed enum. Other enums are None and Identity.

Which can be used with the DatabaseGeneratedOption

  • Computed : The database generates a value when a row is inserted or updated.

  • Identity : The database generates a value when a row is inserted.

  • None : The database does not generate values.

[DatabaseGenerated(DatabaseGenerationOption.Computed)]
public string Something { get; set; }

As you calculate your column server side the correct way is to configure the field at the context level with:

If you use NotMapped , you will not get the value from the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM