我有一个与LINQ更新帐户表到SQL下面的代码。 账户号码是主键列。 这需要更新的唯一价值是ACCOUNTTYPE; 然而,持续时间也被以零(对于int默认值)更新。 我们怎样才能避免这种不必要的覆盖?
注:我使用Attach方法
注:我理解这种现象的原因。 “在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
读:
能否LINQ到SQL忽略上插入未指定的列,以便数据库使用默认值?
我如何绑定枚举,以位或为int的的DbType?
LINQ到SQL:为什么会出现IDENTITY_INSERT错误?
LINQ to SQL的:更新不刷新时“UpdateCheck的=从不”