C# 为什么我会得到;无法为标识列“插入显式值”;当I';我没有为标识列指定值吗?

C# 为什么我会得到;无法为标识列“插入显式值”;当I';我没有为标识列指定值吗?,c#,linq-to-sql,C#,Linq To Sql,我有一张这样的桌子: ClientID是表中唯一的标识列。UserID是不同表主键的FK 以下是我的Linq到SQL插入代码: public void InsertClientByUsername(string username, Entities.Client clientInfo) { using (LinqModelDataContext db = new LinqModelDataContext()) { var existingClient = (

我有一张这样的桌子:

ClientID是表中唯一的标识列。UserID是不同表主键的FK

以下是我的Linq到SQL插入代码:

public void InsertClientByUsername(string username, Entities.Client clientInfo)
{

    using (LinqModelDataContext db = new LinqModelDataContext())
    {

        var existingClient = (from client in db.Clients
                              join ext_usr in db.User_Extendeds on client.UserID equals ext_usr.FriendlyUserID
                              join asp_usr in db.aspnet_Users on ext_usr.UserID equals asp_usr.UserId
                              where asp_usr.UserName.ToLower().Equals(username)
                              select client).SingleOrDefault();

        if (existingClient != null)
        {
            existingClient.Address1 = clientInfo.Address1;
            existingClient.Address2 = clientInfo.Address2;
            existingClient.City = clientInfo.City;
            existingClient.CompanyName = clientInfo.CompanyName;
            existingClient.CountryID = clientInfo.CountryID;
            existingClient.FaxNumber = clientInfo.Fax;
            existingClient.FirstName = clientInfo.FirstName;
            existingClient.LastName = clientInfo.LastName;
            existingClient.MailingAttention = clientInfo.Attention;
            existingClient.PhoneNumber = clientInfo.PhoneNumber;
            existingClient.StateID = clientInfo.StateID;
            existingClient.ZipCode = clientInfo.Zip;

        }
        else
        {
            int userID = (from ext_usr in db.User_Extendeds
                          join asp_usr in db.aspnet_Users on ext_usr.UserID equals asp_usr.UserId
                          where asp_usr.UserName.ToLower().Equals(username)
                          select ext_usr.FriendlyUserID).SingleOrDefault();

            Client newClient = new Client();
            newClient.UserID = userID;
            newClient.Address1 = clientInfo.Address1;
            newClient.Address2 = clientInfo.Address2;
            newClient.City = clientInfo.City;
            newClient.CompanyName = clientInfo.CompanyName;
            newClient.CountryID = clientInfo.CountryID;
            newClient.FaxNumber = clientInfo.Fax;
            newClient.FirstName = clientInfo.FirstName;
            newClient.LastName = clientInfo.LastName;
            newClient.MailingAttention = clientInfo.Attention;
            newClient.PhoneNumber = clientInfo.PhoneNumber;
            newClient.StateID = clientInfo.StateID;
            newClient.ZipCode = clientInfo.Zip;

            db.Clients.InsertOnSubmit(newClient);

        }

        db.SubmitChanges();
    }
}
如果你好奇的话,我之所以有这些赋值是因为我在我的POCO域对象和linq生成的对象之间进行转换。在这个异常的情况下,它采用else语句的路径,创建一个新的客户机

您可以看到,我没有涉及ClientID属性,它是表中唯一的标识列

当identity\u insert设置为OFF时,为什么我在表'Client'中得到“无法为identity列插入显式值”

如果有用,以下是我的stacktrace:

System.Data.SqlClient.SqlException被删除 未由用户代码处理
Message=“无法插入显式值 对于表“客户端”中的标识列 当IDENTITY_INSERT设置为OFF时。“
Source=“.Net SqlClient数据提供程序” 错误代码=-2146232060类=16
行号=1号编号=544
程序=”
Server=“192.168.168.190”State=1
堆栈跟踪: 位于System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔断开连接) 位于System.Data.SqlClient.SqlInternalConnection.OnError(SqlException 异常,布尔断开连接) 位于System.Data.SqlClient.TdsParser.ThroweException和Warning(TdsParserStateObject stateObj) 位于System.Data.SqlClient.TdsParser.Run(RunBehavior 运行行为,SqlCommand cmdHandler, SqlDataReader数据流, BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj) 位于System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,运行行为,字符串 重置选项(字符串) 位于System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior,RunBehavior, 布尔返回流(布尔异步) 位于System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior,RunBehavior, 布尔返回流,字符串方法, DbAsyncResult(结果) 位于System.Data.SqlClient.SqlCommand.InternalExecuteOnQuery(DbAsyncResult 结果,字符串方法名,布尔值 sendToPipe) 位于System.Data.SqlClient.SqlCommand.ExecuteOnQuery()处 在System.Data.Linq.SqlClient.SqlProvider.Execute(表达式 查询,查询信息查询信息, IObjectReaderFactory工厂,对象[] parentArgs,对象[]userArgs, ICompiledSubQuery[]子查询,对象 最后结果) 位于System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(表达式 查询,查询信息[]查询信息, IObjectReaderFactory工厂,对象[] userArguments,ICompiledSubQuery[] 子查询) 位于System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(表达式 (查询) 在System.Data.Linq.ChangeDirector.StandardChangeDirector.DynamicInsert(TrackedObject (项目) 在System.Data.Linq.ChangeDirector.StandardChangeDirector.Insert(TrackedObject)中 (项目) 位于System.Data.Linq.ChangeProcessor.SubmitChanges(冲突模式 故障模式) 位于System.Data.Linq.DataContext.SubmitChanges(冲突模式 故障模式) 在System.Data.Linq.DataContext.SubmitChanges()中 位于DomainModel.Repository.Concrete.SqlClientRepository.InsertClientByUsername(字符串 用户名,客户端clientInfo)


尝试将“自动生成值”设置为false

尝试将
只读设置为
true
在.edmx文件中添加StoreGeneratedPattern=“Identity”(在txt编辑器中查看)

我也遇到了同样的问题,删除表并阅读后解决了它。我不知道解决方案是否漂亮,它确实做到了,而且速度非常快。这很难看,因为Linq to Sql和Visual Studio 2008中有一个bug(在我的情况下,它也可能是其他版本中的bug),但这至少是一个可以存活的bug。

正如@Martin所说,我也遇到了同样的问题,尽管我不必删除整个图表来修复它。我所要做的就是强制图表重新生成代码。这通常只是更改图表上的某些内容并将其更改回来。在更严重的情况下,我必须重新启动VS,甚至重新启动引导设计器重新生成代码。

我也遇到了同样的问题,但清除实体并将其导入回并没有起到让be不得不深入挖掘的作用。这里真正的问题是,在实体图的SSDL内容下缺少一个属性(StoreGeneratedPattern=“Identity”)该属性应位于实体的ID属性上。添加此属性后,应设置所有属性

例如:

<EntityType Name="TABLENAME">
  <Key>
    <PropertyRef Name="ID" />
  </Key>
  <Property Name="ID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
</EntityType>


我在visual studio中从*.dbml中删除了该表并再次插入。上述问题已解决!

您可以使用SQL Profiler查看生成的SQL。但L2S正在生成值这一点毫无疑问。请查看生成代码(Project | Show All files)要查看ClientId列的元数据是否真的具有适当的“标识标记”(它是musnt,或者一定存在一些文件版本混淆…)@Ruben Bartelink,出于某种原因,它在我生成的代码中是一个奇怪的错误。我删除了我的数据上下文并重建了它,这次它成功了。奇怪。我也有同样的问题……我猜是SqlDesigner问题。如果您选择列并查看它的属性(至少在VS 2012中),它也可以在edmx的可视化编辑器中使用。