views:

160

answers:

2

I'm getting

System.NotSupportedException: All objects in the EntitySet 'Entities.Message' must have unique primary keys. However, an instance of type 'Model.Message' and an instance of type 'Model.Comment' both have the same primary key value

but I have no idea what this means.

Using EF4, I have a bunch of entities of type Message. Some of these messages are actually a subtype, Comment, inheritance by table-per-type. Just

 DB.Message.First();

will produce the exception. I have other instances of subtyping where I don't experience problems but I can't see any discrepencies. Sometimes, though, the problem goes away if I restart the development server, but not always.

Edit: I've worked out (should have before) that the problem is a fault of the stored procedure fetching my Messages. The way this is currently set up as that all the fields pertaining to Message is fetched, the Comment table is ignored by the sproc. The context then proceeds to muck this up, probably by fetching those Messages that are also Comments again, as you suggested. How to do this properly is the central issue at hand. I've found some indications to a solution at http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/bb0bb421-ba8e-4b35-b7a7-950901adb602.

A: 

I am not an EF kind of guy (busy working with NHibernate, haven't had time to get up to date with EF yet) so I may be totally wrong here, but could the problem be that the two tables (since you are using inheritance by table-per-type) have primary keys that collide?

If you check the data in both tables, do primary key values collide?

Andreas Paulsson
Well, yes, as they should. If you don't believe me, believe EF. There's a nifty little command called "Build database from model"...
Martin
A: 

It sounds like you are pulling two records into memory one into message and one into comment.

Possible prblems:

  • There are two physical messages with the same id
  • The same message is being pulled up as a message and a comment
  • The same message is being pulled up twice into the same context

That the problem sometimes goes away when you restart, points to a problem with cleaning up of context. Are you using "using" statements.

Do you have functionality for changing from a message to a comment?

Shiraz Bhaiji
No, there's no such functionality. please see edit.
Martin