c# - Update record if it exists -


i'm new ef, , i'm trying understand best way handle inserting , updating data. context, i'm using .net mvc website boiler plate, , i've created customers table 1:1 relationship aspnetusers. i've created view manage customer data.

here httppost actionresult:

    [httppost]     [validateantiforgerytoken]     public async task<actionresult> addcard(external.stripe.customer customer)     {         if (!modelstate.isvalid)         {             return view(customer);         }          external.stripe.customeroperations co = new external.stripe.customeroperations();         customer = co.create(customer);          var user = usermanager.findbyid(user.identity.getuserid());         customer.userid = user.id;          var context = new external.stripe.customercontext();           context.customers.add(customer);         context.savechanges();          return redirecttoaction("index", "manage");     } 

i feel i'm going down wrong path, because if make updates customer model, need check ef if key exists, , if does, run update instead. figured ef have native way of saving model if needs updated. don't know if persist model, or if better placed somewhere else in code.

short answer

...if make updates customer model, need check ef if key exists, , if does, run update instead.

addorupdate() this. docs:

adds or updates entities key when savechanges called. equivalent "upsert" operation database terminology

example

in other words, change code this:

context.customers.addorupdate(c => c.userid, customer); context.savechanges(); 

in above example, c => c.userid expression specifying userid should used when determining whether add or update operation should performed.

considerations

  • addorupdate() matches database tables based on arbitrary, user supplied key value. in example, key userid. sure use appropriate key.
  • addorupdate() updates all entity values , sets database cells null properties lack value. sure set property values of object (e.g. customer) before using it.

see also

update row if exists else insert logic entity framework has few answers talk 4 or more different approaches.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -