Default Values (of C# variables) Issue in LINQ to SQL Update

后端 未结 2 1086
刺人心
刺人心 2020-12-11 13:04

I have the following code for updating Account table with LINQ to SQL. AccountNumber is the primary key column. The only value which need to be updated is AccountType; howev

相关标签:
2条回答
  • 2020-12-11 13:09

    I solved this issue by changing the update approach by following the answer in LINQ to SQL: Updating without Refresh when “UpdateCheck = Never”

    UpdateCheck is set as Never for the Duration column

        public void UpdateAccount()
        {
            //Used value from previous select
            DateTime previousDateTime = new DateTime(2012, 6, 26, 11, 14, 15, 327);
            int prevDuration = 0;
    
            RepositoryLayer.Account accEntity = new RepositoryLayer.Account();
            accEntity.AccountNumber = 1; //Primary Key
            accEntity.ModifiedTime = previousDateTime; //Concurrency column
            //accEntity.Duration = prevDuration;
    
            accountRepository.UpdateChangesByAttach(accEntity);
    
            //Values to be modified after Attach
            accEntity.AccountType = "WIN-WIN";
            accEntity.ModifiedTime = DateTime.Now;
    
            try
            {
                accountRepository.SubmitChanges();
            }
            catch(System.Data.Linq.ChangeConflictException e)
            {
                throw new Exception(e.Message);
            }
    
        }
    
    
       public virtual void UpdateChangesByAttach(T entity)
        {
    
            if (Context.GetTable<T>().GetOriginalEntityState(entity) == null)
            {
                //If it is not already attached
                Context.GetTable<T>().Attach(entity);
            }
    
        }
    

    Generated SQL

    UPDATE [dbo].[Account]
    SET [AccountType] = @p2, [ModifiedTime] = @p3
    WHERE ([AccountNumber] = @p0) 
          AND ([ModifiedTime] = @p1)
    
    -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1]
    -- @p1: Input DateTime (Size = -1; Prec = 0; Scale = 0) [6/26/2012 11:14:15 AM]
    -- @p2: Input NChar (Size = 10; Prec = 0; Scale = 0) [WIN-WIN]
    -- @p3: Input DateTime (Size = -1; Prec = 0; Scale = 0) [6/26/2012 11:16:29 AM]
    
    0 讨论(0)
  • 2020-12-11 13:22

    This should do:

    int number = 4;
    var acc1 = new accountRepository.Accounts.Where(a => a.Number == number).FirstOrDefault();
    
    if (acc1 == null)
    {
        // Not found by ID, create new
        acc1 = new RepositoryLayer.Account();
        acc1.Number = number;
        accountRepository.Accounts.AddObject(acc1);
    }
    
    acc1.AccountType = "Verify";
    
    accountRepository.SubmitChanges();
    
    0 讨论(0)
提交回复
热议问题