本文介绍了由于没有主键,因此无法对表执行创建,更新或删除操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在表中插入具有标识列RequestID(也是主键)的行

I've been trying to insert row in the table having an identity column RequestID (which is primary key as well)

    HelpdeskLog logEntry = new HelpdeskLog { RequestBody = message.Body };
    if (attachment != null)
        logEntry.Attachments = Helper.StreamToByteArray(attachment.ContentStream);
    Database.HelpdeskLogs.InsertOnSubmit(logEntry);

但是我的代码不可避免地会引发以下错误

But my code inevitably throws following error

尽管主键列确实存在

这就是我试图做的:

  1. 要在调试器中查看在对象模型中插入的标识列的值.是0
  2. 要手动(使用SQL)将伪造的值插入表中-工作正常,可以按预期生成标识值
  3. 确保SQLMetal是否已正确生成表映射.一切正常,主键属性正确生成

尽管如此,两种方法都无济于事.诀窍是什么,有人知道吗?

Nevertheless, neither of approaches helped. What's the trick, does anybody know?

推荐答案

我在C#代码中也遇到了这个问题,并且意识到我忘记了IsPrimaryKey名称:

I've also had this problem come up in my C# code, and realized I'd forgotten the IsPrimaryKey designation:

  [Table (Name = "MySessionEntries" )]
  public class SessionEntry
  {
     [Column(IsPrimaryKey=true)]  // <---- like this
     public Guid SessionId { get; set; }
     [Column]
     public Guid UserId { get; set; }
     [Column]
     public DateTime Created { get; set; }
     [Column]
     public DateTime LastAccess { get; set; }
  }

即使您的数据库表(在这种情况下为 MySessionEntries )已经定义了主键,也需要

,因为除非您使用过linq2sql工具,否则Linq不会自动找出该事实.将您的数据库定义导入Visual Studio.

this is needed even if your database table (MySessionEntries, in this case) already has a primary key defined, since Linq doesn't automagically find that fact out unless you've used the linq2sql tools to pull your database definitions into visual studio.

这篇关于由于没有主键,因此无法对表执行创建,更新或删除操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:34