Gopi P
Gopi P

Reputation: 437

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.

Upvotes: 2

Views: 3646

Answers (2)

TheGeneral
TheGeneral

Reputation: 81543

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

Upvotes: 5

tschmit007
tschmit007

Reputation: 7800

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.

Upvotes: 1

Related Questions