0

I'm defining POCO's, used with the Code First capabilities of Entity Framework 4.0.

Part of my data comes from an external source, and for that data I need to keep the identity column value identical to that of the external source, I sometimes need to set the ID myself. But for the same entities I sometimes don't have an Id and would like an Auto increment like behavior.

Is it possible to define the POCO in such a way, that when I set the value it would use it, and when I don't, it would auto increment? According to this mySQL forum answer mySQL is supposed to handle this scenario pretty well, but it seems that with the Entity Framwork doesn't...

RonyK
  • 2,644
  • 5
  • 32
  • 42

2 Answers2

0

I think what you're looking for is Identity Insert.

Check this link out: Using IDENTITY_INSERT with EF4

As for defining the POCO in such a way, that it would automatically know what your intent is - I don't think that's possible. You would have to definitely set that explicitly when doing the inserts.

What I would do is run raw SQL against the tables with EF, where I'd set Identity Insert = ON, then insert some lines in there, and then set it back to off.

Remember to take into account that your auto incrementing ID might eventually end up having the same values as you've used in your manual inserts, which will in essence break your program.

Best regards, Lari

Community
  • 1
  • 1
Lari Tuomisto
  • 198
  • 1
  • 1
  • 11
0

Following on from Lari's answer, I would suggest writing a stored procedure which sets identity_insert on, inserts records and then off afterwards.

I'd then import that as a function import and then using that inside perhaps an extension method on the entity type itself, or just as a function on the object context.

That way you can a standard:

var user = new User("John"); 
entities.Add(user);
entities.SaveChanges(); 

Type thing, when you want to use the auto incrementing number, and then use something like:

entities.CreateUser("John"); // This would be the SP

That way you could conditionally use one method or the other. It's not automatic, but would enable you to use either.

dougajmcdonald
  • 19,231
  • 12
  • 56
  • 89