How to combine the Add and Update operations?

Jun 20, 2010 at 10:57 AM

Hi,

I'm trying to combine the operations for Add and Update. Though I'm not quite sure how to structure the if statement to pick this up:

 

If Record/Persistent object exists already - UPDATE.

Else Add.

Having trouble trying to create the code for this, any suggestions?

 

thanks.

 

 

 

Coordinator
Jun 22, 2010 at 3:16 AM

Hi, could you elaborate a bit more? Thanks

Jun 22, 2010 at 3:43 AM

Hi :) sure. 

Well, say I'd like to create my Add and Update operations for persistent objects.

I might have a persistent object called Actor. You can have many actors being paid a certain rate (which is another persistent object Rate).

I understand that Actor would then be considered an inner object of Rate. 

Actor may have an id and a name.

To Add an actor, I'd code the following:

public Rate[] Rates()        

{
      return ContextFactory.Context.GetObjectSet<Rate>().ToArray();                

 }

 public void Add_Rate(String name)        
{            

ContextFactory.Context.PersistChanges<Rate>(new Rate { Name = name });            //Insert new rate;        
}

public void Add_Actor()        
{
ObjectContext context = ContextFactory.Context;
Actor tomcruise = new Actor { Name = "Tom Cruise", Age = 43, Enrolled = true };            

            Rate rate = context.GetObjectSet<Rate>().ToArray()[1];            
Actor x = rate.Actors[0];            

rate.Add_Actor(tomcruise);
context.PersistChanges<Country>(country);             
context.Commit();        }

public void Update_Actor()     

{            
ObjectContext context = ContextFactory.Context;            
Rate rate = context.GetObjectSet<Rate>().ToArray()[1];            
Actor x = rate.Actors[0];
x.Name = "Last Samurai";
context.PersistChanges(x);
context.Commit();

}            

Basically, I;d like to combine these methods so that the code checks first if the record already exists (by looking up the actor ID), and inserting the new record if it does not, but updating this record if it does.

I hope this makes sense? I'm a little confused :(.

 

 

 

 

 

 

 

 

 

 

 

Jun 22, 2010 at 3:44 AM

Thank you for making many web programmers lives much much easier!!

Coordinator
Jun 23, 2010 at 2:14 AM

You can just put both in a list and give the list to the PersistChanges. The method will take the list and persist the changes...

Jun 23, 2010 at 3:31 AM

How do I check if it exists?

if((context.GetObject<Actor>["ID=0"]) == null)   ?

 

Coordinator
Jun 24, 2010 at 3:59 AM

Yes.

Jun 24, 2010 at 4:38 AM

great, thanks ^_^