Can't perform Create, Update or Delete operations on Table because it has no primary key

igor picture igor · Apr 10, 2009 · Viewed 27.5k times · Source

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

Can't perform Create, Update or Delete operations on Table because it has no primary key.

despite primary key column exists indeed

That's what I tried to do:

  1. To look in debugger the value of identity column being inserted in object model. It is 0
  2. To insert manually (with SQL) fake values into table - works fine, identity values generated as expected
  3. To assure if SQLMetal has generated table map correctly . All OK, primary key attribute is generated properly

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

Answer

Steve L picture Steve L · Jul 13, 2009

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; }
  }

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.