身份插入和 LINQ to SQL

时间:2023-02-17
本文介绍了身份插入和 LINQ to SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 SQL Server 数据库.该数据库有一个名为 Item 的表.项目有一个名为ID"的属性.ID 是我桌子上的主键.此主键是一个增量值为 1 的 int.当我尝试插入记录时,我收到一条错误消息:

I have a SQL Server database. This database has a table called Item. Item has a property called "ID". ID is the primary key on my table. This primary key is an int with an increment value of 1. When I attempt to insert the record, I receive an error that says:

当 IDENTITY_INSERT 设置为 OFF 时,无法为表 'Item' 中的标识列插入显式值.".

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

我正在尝试使用以下代码插入记录:

I am attempting to insert records using the following code:

  public int AddItem(Item i)
  {
    try
    {
      int id = 0;
      using (DatabaseContext context = new DatabaseContext())
      {
        i.CreatedOn = DateTime.UtcNow;
        context.Items.InsertOnSubmit(i);
        context.SubmitChanges();
        id = i.ID;
      }
      return id;
    }
    catch (Exception e)
    {
      LogException(e);
    }
  }

当我在提交之前查看 i.ID 时,我注意到 i.ID 设置为 0.这意味着我试图插入 0 作为身份.但是,我不确定它应该是什么.有人可以帮我吗?

When I look at i.ID before submitting it, I notice that i.ID is set to 0. Which would imply that I'm trying to insert 0 as the identity. However, I'm not sure what it should be. Can someone help me out?

谢谢!

推荐答案

听起来好像您的模型没有意识到它一个身份;ID 列应标记为 db-generated(Auto Generated Value 在 UI 中,或 IsDbGenerated 在 xml 中),并且可能作为首要的关键.然后它不会尝试插入它,并在写入后正确更新值.

It sounds simply as though your model is unaware of the fact that it is an identity; the ID column should be marked as db-generated (Auto Generated Value in the UI, or IsDbGenerated in the xml), and probably as the primary key. Then it will not attempt to insert it, and will update the value correctly after it is written.

这篇关于身份插入和 LINQ to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:简单的 linq to sql 不支持转换为 SQL 下一篇:不支持 Last 和 LastOrDefault

相关文章

最新文章