gpt4 book ai didi

c# - Linq 到 SQL : Why am I getting IDENTITY_INSERT errors?

转载 作者:太空狗 更新时间:2023-10-29 20:48:09 25 4
gpt4 key购买 nike

我正在使用 Linq to SQL。我有一个 DataContext,我正在对它进行 .SubmitChanges()'ing。插入身份字段出错:

Cannot insert explicit value for identity column in table 'Rigs' when IDENTITY_INSERT is set to OFF.

The only identity field is "ID", which has a value of 0. It's defined in the DBML as:

[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]

有几个外键,我已经验证它们的值与外部表的内容一致。

为什么会出现此错误?

编辑:这里是查询:

exec sp_executesql N'INSERT INTO [dbo].[Rigs]([id], [Name], [RAM], [Usage], [MoreInfo], [datetime], [UID])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6)
SELECT [t0].[id], [t0].[OSID], [t0].[Monitors]
FROM [dbo].[Rigs] AS [t0]
WHERE [t0].[id] = @p7',N'@p0 int,@p1 varchar(1),@p2 int,@p3 varchar(1),@p4 varchar(1),@p5 datetime,@p6 int,@p7
int',@p0=0,@p1='1',@p2=NULL,@p3='4',@p4='5',@p5=''2009-03-11 20:09:15:700'',@p6=1,@p7=0

很明显它传递了一个零,尽管它从未被赋值。

编辑:添加代码:

Rig rig = new Rig();
int RigID;
try
{ // Confirmed these always contain a nonzero value or blank
RigID = int.Parse(lbSystems.SelectedValue ?? hfRigID.Value);
if (RigID > 0) rig = mo.utils.RigUtils.GetByID(RigID);
}
catch { }

rig.Name = Server.HtmlEncode(txtName.Text);
rig.OSID = int.Parse(ddlOS.SelectedValue);
rig.Monitors = int.Parse(txtMonitors.Text);
rig.Usage = Server.HtmlEncode(txtUsage.Text);
rig.MoreInfo = Server.HtmlEncode(txtMoreInfo.Text);
rig.RigsToVideoCards.Clear();
foreach (ListItem li in lbYourCards.Items)
{
RigsToVideoCard r2vc = new RigsToVideoCard();
r2vc.VCID = int.Parse(li.Value);
rig.RigsToVideoCards.Add(r2vc);
}
rig.UID = c_UID > 0 ? c_UID : mo.utils.UserUtils.GetUserByToken(this.Master.LiveToken).ID;

if (!mo.utils.RigUtils.Save(rig))
throw new ApplicationException("There was an error saving your Rig. I have been notified.");
hfRigID.Value = rig.id.ToString();

public static User GetUserByToken(string token)
{
DataClassesDataContext dc = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["MultimonOnlineConnectionString"].ConnectionString);
return (from u in dc.Users
where u.LiveToken == token
select u).FirstOrDefault();
}

另外,我注意到当我更新现有装备时 (insertonsubmit),它不会更新。 Profiler 甚至不显示正在运行的任何查询。

最佳答案

我对发生的事情的理论如下:

  1. 您设计并创建了数据库
  2. 您在 Visual Studio 中使用 LINQ TO SQL 创建了数据库上下文
  3. 您忘记为您的表设置自动识别
  4. 你通过进入你的数据库并设置自动识别来解决这个问题
  5. 但是您忘记重新创建/更新您的 LINQ TO SQL DB 上下文!!!

:D

关于c# - Linq 到 SQL : Why am I getting IDENTITY_INSERT errors?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com