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

后端 未结 2 1090
刺人心
刺人心 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().GetOriginalEntityState(entity) == null)
            {
                //If it is not already attached
                Context.GetTable().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]
    

提交回复
热议问题