当我没有为标识列指定值时,为什么我在LINQ to SQL中获得“无法为标识列插入显式值”?

时间:2009-08-05 14:36:19

标签: c# linq-to-sql

我有一个看起来像这样的表: alt text

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

这是我的Linq to 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语句的路径,创建一个新客户端。

您可以看到我 NOT 触摸ClientID属性,该属性是表中的〜唯一〜标识列。

当IDENTITY_INSERT设置为OFF时,为什么我收到“无法在表'Client'中为标识列插入显式值?

如果它有用,这是我的stacktrace:

  

System.Data.SqlClient.SqlException是   未按用户代码处理
  Message =“无法插入显式值   表'客户'中的标识列   当IDENTITY_INSERT设置为OFF时。“
  Source =“。Net SqlClient Data Provider”   ErrorCode = -2146232060等级= 16
  LineNumber = 1 Number = 544
  过程= “”
  Server =“192.168.168.190”State = 1
  堆栈跟踪:          在System.Data.SqlClient.SqlConnection.OnError(SqlException   exception,Boolean breakConnection)          在System.Data.SqlClient.SqlInternalConnection.OnError(SqlException   exception,Boolean breakConnection)          在System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject)   stateObj)          在System.Data.SqlClient.TdsParser.Run(RunBehavior   runBehavior,SqlCommand cmdHandler,   SqlDataReader dataStream,   BulkCopySimpleResultSet   bulkCopyHandler,TdsParserStateObject   stateObj)          在System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader   ds,RunBehavior runBehavior,String   resetOptionsString)          在System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior   cmdBehavior,RunBehavior runBehavior,   Boolean returnStream,Boolean async)          在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior   cmdBehavior,RunBehavior runBehavior,   Boolean returnStream,String方法,   DbAsyncResult结果)          在System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult   result,String methodName,Boolean   sendToPipe)          在System.Data.SqlClient.SqlCommand.ExecuteNonQuery()          在System.Data.Linq.SqlClient.SqlProvider.Execute(表达式   查询,QueryInfo queryInfo,   IObjectReaderFactory工厂,对象[]   parentArgs,Object [] userArgs,   ICompiledSubQuery [] subQueries,Object   的lastResult)          在System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression   query,QueryInfo [] queryInfos,   IObjectReaderFactory工厂,对象[]   userArguments,ICompiledSubQuery []   子查询)          在System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression   查询)          at System.Data.Linq.ChangeDirector.StandardChangeDirector.DynamicInsert(TrackedObject   项目)          在System.Data.Linq.ChangeDirector.StandardChangeDirector.Insert(TrackedObject)   项目)          在System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode   故障模式)          在System.Data.Linq.DataContext.SubmitChanges(ConflictMode   故障模式)          在System.Data.Linq.DataContext.SubmitChanges()          在DomainModel.Repository.Concrete.SqlClientRepository.InsertClientByUsername(String   用户名,客户端clientInfo)

7 个答案:

答案 0 :(得分:4)

在.edmx文件中添加StoreGeneratedPattern =“Identity”(在txt编辑器中查看)

答案 1 :(得分:1)

来自here

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

答案 2 :(得分:1)

我也有同样的问题,删除表并阅读它修复它。我不知道他的解决方案不是很漂亮,它肯定能解决问题而且非常快。它的丑陋是Linq-to-Sql和Visual Studio 2008中的一个错误(在我的情况下,它也可能是其他版本中的错误),但它至少是一个适合居住的bug。

答案 3 :(得分:1)

我有同样的问题,但是消灭实体并将其导回后并没有为我做的伎俩导致必须深入挖掘。这里真正的问题是,在您的实体图的SSDL内容下,有一个缺少的属性(StoreGeneratedPattern =“Identity”)应该在您的实体的ID属性上。添加此属性后,您应该全部设置。

示例:

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

答案 4 :(得分:1)

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

答案 5 :(得分:0)

尝试将Read Only设为true

答案 6 :(得分:0)

正如@Martin所说,虽然我没有删除整个图表来修复它,但我遇到了同样的问题。我所要做的就是强制图重新生成代码。这通常只是在图表上更改某些内容并将其更改回来。在更严重的情况下,我不得不重启VS甚至重启以让设计人员重新生成代码。

相关问题