none
Why is there no "UpdateOnSubmit" method?

    Question

  • I can queue up a series of Inserts via the "UpdateOnSubmit" method that are transacted on "SubmitChanges", with a transaction rollback if any fail. However, I am confused on how updates are managed as there does not seem to be an equilivent "UpdateOnSubmit" that can be included in the SubmitChanges collection.

    I seem to be missing something basic here. Can someone explain how I would do something like:

    dctx.customer.InsertOnSubmit(cust);
    dctx.vehicle.UpdateOnSubmit(veh);
    dctx.stock.InserOnSubmit(stock);

    dctx.SubmitChanges(ConflictMode.ContinueOnConflict);

    Wednesday, January 28, 2009 3:18 PM

All replies

  • LINQ to SQL does automatic change tracking, so it is already aware of changes you've made to objects you've retrieved via the DataContext. A request to update the object during SubmitChanges is implied. It also knows when you've created a new instance of an object and associated it with an object that it is already tracking (via a relationship property), so in those cases you don't even need to call InsertOnSubmit. 

     


    Wayward LINQ Lacky
    Wednesday, January 28, 2009 4:11 PM
  • Does this mean that I have to first do a query for the existing rec? Or will merely instantiating a new Entity and making changes to it do the trick, such as

    t_customer cust = new t_customer();

    cust.uid = 12345;
    cust.LastName = "Newname";

    dctx.SubmitChanges();

    If uid is the PK, then the only change I want to make in the update is a new lastname.

    Wednesday, January 28, 2009 6:27 PM
  • If you are creating a new instance to do an update (w/o first retrieving it via a query) you need to use Attach() to tell the change tracking system about it.

    t_customer cust = new t_customer();
    cust.uid = 12345;
    cust.LastName = "OldName";
    cust.XXX = ...;

    dctx.Customers.Attach(cust);

    cust.LastName = "Newname";

    dctx.SubmitChanges();

    Note, that doing it this was is 'simulating' the situation where you retrieved the object from the database. You have to assign all the fields with the expected old values because SubmitChanges will send a command that will only succeed at updating if the corresponding row in the database still has all the expected values.  You can turn off update checking by either setting UpdateCheck=UpdateCheck.Never in the mapping (attributes or map file) or in the DBML that will generate the mapping.  Or if you have a version field declared in the mapping, L2S will only use that field for the update check, so you'll only have to get that field right.


    Wayward LINQ Lacky
    Thursday, January 29, 2009 4:57 PM