【问题标题】:Default Values (of C# variables) Issue in LINQ to SQL UpdateLINQ to SQL 更新中的默认值(C# 变量)问题
【发布时间】:2012-06-25 09:39:02
【问题描述】:

我有以下代码用于使用 LINQ to SQL 更新 Account 表。 AccountNumber 是主键列。唯一需要更新的值是 AccountType;但是 Duration 也会更新为零(int 的默认值)。我们如何避免这种不必要的覆盖?

注意:我使用的是附加方法

注意:我理解这种行为的原因。 “DataContext 无法区分分配值为零的字段和仅未分配的字段。”。我正在寻找解决方案来克服这个问题。

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Duration", DbType="Int NOT NULL"
public int Duration

表数据

表结构:

 CREATE TABLE [dbo].[Account](
[AccountNumber] [int] NOT NULL,
[AccountType] [nchar](10) NOT NULL,
[Duration] [int] NOT NULL,
[DepositedAmount] [int] NULL,
 CONSTRAINT [PK_Account] PRIMARY KEY CLUSTERED 
 (
[AccountNumber] ASC
 )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
 ) ON [PRIMARY]

代码

    public void UpdateAccount()
    {
        RepositoryLayer.Account acc1 = new RepositoryLayer.Account();
        acc1.AccountNumber = 4;
        acc1.AccountType = "Verify";

        accountRepository.UpdateChangesByAttachAndRefresh(acc1);
        accountRepository.SubmitChanges();

    }


    public virtual void UpdateChangesByAttachAndRefresh(T entity)
    {

        //Can GetOriginalEntityState cause any bug? Is it unnecessary?           
        if (GetTable().GetOriginalEntityState(entity) == null)
        {
            //If it is not already attached

            Context.GetTable<T>().Attach(entity);
            Context.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, entity);


        }

    }

生成的 SQL

UPDATE [dbo].[Account]
SET [AccountType] = @p3, [Duration] = @p4
WHERE ([AccountNumber] = @p0) 
AND ([AccountType] = @p1) 
AND ([Duration] = @p2) 
AND ([DepositedAmount] IS NULL)

-- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [4]
-- @p1: Input NChar (Size = 10; Prec = 0; Scale = 0) [TEST      ]
-- @p2: Input Int (Size = -1; Prec = 0; Scale = 0) [10]
-- @p3: Input NChar (Size = 10; Prec = 0; Scale = 0) [Verify]
-- @p4: Input Int (Size = -1; Prec = 0; Scale = 0) [0]

-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1

阅读:

  1. Can LINQ-to-SQL omit unspecified columns on insert so a database default value is used?

  2. How can I bind an Enum to a DbType of bit or int?

  3. Linq to SQL: Why am I getting IDENTITY_INSERT errors?

  4. LINQ to SQL: Updating without Refresh when “UpdateCheck = Never”

【问题讨论】:

    标签: c# .net sql-server linq linq-to-sql


    【解决方案1】:

    应该这样做:

    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();
    

    【讨论】:

    • 谢谢。我们不能在使用“附加”和刷新方法时实现它吗?
    • @Lijo:Attach 过去只是给我带来了问题。使用上述方法而不是;p
    • @leppie 你能列出这些问题或提供参考吗?
    【解决方案2】:

    我通过按照LINQ to SQL: Updating without Refresh when “UpdateCheck = Never”中的答案更改更新方法解决了这个问题

    Duration 列的 UpdateCheck 设置为从不

        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);
            }
    
        }
    

    生成的 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多