Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert/Update Entity in EF?

I am writing a crawler that should go to a website, extract some data from there and then store it into a db, the thing is the crawler should also update the data that has already been found in a prior run.

The ParseDataPage returns the information parsed from the site in a EF POCO, one of its properties is a unique identifier (which also is the primary key in the db table), how can I tell EF to insert/add the object?

class Program
{
    static void Main()
    {

        var context = (adCreatorEntities) DbContextFactory.GetInstance().GetDbContext<adCreatorEntities>();
        var crawler = new DataCrawler();            
        crawler.Login();
        var propertyIds = crawler.GetPropertyIds();

        foreach (var id in propertyIds)
        {
            var poco = crawler.ParseDataPage(id);
            context.Properties.Add(poco); //<-- How can I tell EF to update if the record exists or to insert it otherwise??
            context.SaveChanges();
        }

        context.SaveChanges();

        if (crawler.LoggedIn)
            crawler.Logout();
    }
}
like image 218
David Sarmiento Avatar asked Jul 03 '26 08:07

David Sarmiento


1 Answers

You can set the entity state to Modified or Add the entity to the DbSet based on the key's value.

if(entity.propertyId <= 0)
{
    context.Properties.Add(poco); 
}
else
{
      context.Entry(poco).State = EntityState.Modified;
}

This is code for EF5, EF4 is slightly different for setting object state

context.ObjectStateManager.ChangeObjectState(poco, EntityState.Modified);
like image 183
James Sampica Avatar answered Jul 04 '26 21:07

James Sampica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!