none
LINQ to SQL - Update and Insert in one C# method RRS feed

Answers

  • Hi Haamakumba,

    Thanks for your post and welcome to MSDN forums.

    Do you mean you want to insert and update records in one method ? like this :

    private void InsertAndUpdate()
    {
      NorthwindDataContext db = new NorthwindDataContext();
    
      //Insert a record
    
      Customer newCus = new Customer();
      newCus.CustomerID = "YYYZZ";
      newCus.CompanyName = "Company_Z";
    
      db.Customers.InsertOnSubmit(newCus);
      db.SubmitChanges();      
      
      
      //Update a record
      Customer record = (from p in db.Customers
             where p.CustomerID == "12345" 
             select p).SingleOrDefault();
    
      Console.WriteLine(default(Customer));
      if (record != default(Customer))
      {
        record.CompanyName = "Company_A";
      }
    
      db.SubmitChanges();
    }
    

    Best regards,
    Alex Liang


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Tuesday, June 22, 2010 6:25 AM
    Moderator

All replies

  • recordtype record = (from tbl in context.tablenames
                   where tbl.key == somevalue
                   select tbl).SingleOrDefault();
    
    if (record == default (recordtype))
    {
    record = new recordtype();
    // populate the base fields
    }
    
    // make required updates
    
    context.SubmitChanges();
    Monday, June 21, 2010 10:36 AM
  • Hi Haamakumba,

    Thanks for your post and welcome to MSDN forums.

    Do you mean you want to insert and update records in one method ? like this :

    private void InsertAndUpdate()
    {
      NorthwindDataContext db = new NorthwindDataContext();
    
      //Insert a record
    
      Customer newCus = new Customer();
      newCus.CustomerID = "YYYZZ";
      newCus.CompanyName = "Company_Z";
    
      db.Customers.InsertOnSubmit(newCus);
      db.SubmitChanges();      
      
      
      //Update a record
      Customer record = (from p in db.Customers
             where p.CustomerID == "12345" 
             select p).SingleOrDefault();
    
      Console.WriteLine(default(Customer));
      if (record != default(Customer))
      {
        record.CompanyName = "Company_A";
      }
    
      db.SubmitChanges();
    }
    

    Best regards,
    Alex Liang


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Tuesday, June 22, 2010 6:25 AM
    Moderator