João Pedro
João Pedro

Reputation: 439

How can I make Entity Framework only update object dependencies?

I'd like to know how can I make Entity Framework update an object instead of always inserting a new one for each new main object.

For example:

I have these objects:

Main Object:

public class ExtraArticleAttributes
{
    [Key]
    public int extraarticleattributes_id { get; set; }
    virtual public WorldData world_data { get; set; }
}

Its dependencie:

public class WorldData
{
    [Key]
    public int worlddata_id { get; set; }
    public string country { get; set; }

So, how can I make Entity Framework when inserting a new ExtraArticleAttributes verify if already exists a WorldData object and only update it?

I've been reading some articles about it and I notice that Entity Framework identify an existing object in DB with a HASH code, so when I get it from an API, and try to insert It in the DB, even though the object has the same data, the Entity Framework doesn't recognize like an existed object in DB. Does exist a way of make It, without spending request to the DB to verify if the object exists, if true get It.

Upvotes: 0

Views: 344

Answers (1)

OJ Raqueño
OJ Raqueño

Reputation: 4561

Set the entity state to Modified:

using System.Data.Entity;

// Assuming that there is already an existing WorldData record in the database with id 1 and country 'foo', and you want to change the country to 'bar'

using (var context = new MyContext())
{
    var extraArticleAttributes = new ExtraArticleAttributes
    {
        world_data = new WorldData
        {
            worlddata_id = 1,
            country = "bar"
        }
    };

    db.ExtraArticleAttributes.Add(extraArticleAttributes);
    db.Entry<WorldData>(extraArticleAttributes.world_data).State = EntityState.Modified;

    db.SaveChanges();

    // world data 1 country is now 'bar'
}

Upvotes: 1

Related Questions