Sandi Horvat
Sandi Horvat

Reputation: 497

How to update certain columns in db with EF

I am filling my database from json responses with entity framework. Now I also have to update my existing values, or if they allready exists, I have to add them. So if Meeting ID exist, update Attending else add.

My method for adding is working corectlly, but I don't know how to update my values.

Here's my code:

foreach (Event eventItem in obj.events)
{                                         
    using (Entities1 ctx = new Entities1())
    {
        Event1 sas = new Event1
        {
            // ID= autoincr
            // some custom values


            MeetingID=eventItem.eventId   
            //Values to update                            
            Attending=eventItem.attendingCount

        };           
            ctx.Event1.Add(sas);
            ctx.SaveChanges();

    }

}

Upvotes: 1

Views: 59

Answers (2)

Aron
Aron

Reputation: 15772

If you know if the item you are trying to Upsert is new/existing. This is the correct code to write.

It is able to do the work in much fewer database calls, resulting in much faster transactions.

using(var ctx = new Context())
{
    foreach (Event eventItem in obj.events)
    {                                         

         Event1 sas = new Event1
         {
             // ID= autoincr
             // some custom values


             MeetingID=eventItem.eventId   
             //Values to update                            
             Attending=eventItem.attendingCount

         }; 
         if(eventItem.eventId != null)
         {          
                ctx.Event1.Add(sas);
         }
         else
         {
                ctx.Entry(sas).State = EntityState.Updated;
         }
    }
    ctx.SaveChanges();
}

Upvotes: 1

teo van kot
teo van kot

Reputation: 12491

You should get your entities from DB if the are exists:

using (Entities1 ctx = new Entities1())
{
    foreach (Event eventItem in obj.events)
    {                                         
        var ev = ctx.Event1.FirstOrDefault(x=>x.eventId == eventItem.eventId); //get your entity from db (maby you should use other ID)
        if(ev == null) //If have no elements add
        {
            Event1 sas = new Event1
            {
                // ID= autoincr
                // some custom values
                MeetingID=eventItem.eventId,
                //Values to update                            
                Attending=eventItem.attendingCount
            };           
            ctx.Event1.Add(sas);
        }
        else // Else just update
        {
            ev.Attending = eventItem.attendingCount;
        }
    }
    ctx.SaveChanges();
}

Also - it's better not create context for each object so i wrap whole peace of your code in context. This way all changes will be in one transaction.

Upvotes: 2

Related Questions