0

Basically I have a product entity

public class Product
{
    public int ID {get; set;}
    public string Name {get; set;}
}

And I want to create :

UnknownProduct : Product
{
    public UnknownProduct()
    {
        ID = -2;
        Name = Unknown;
    }
}

The objective here is to easily create UnknownProduct from the business logic. I want to have this in the resulting table :

#Products 
ID | Name
1  | Beer // Referenced X times
2  | Soda // Referenced Y times
-1 | UnknownProduct // Referenced Z times, so only one row has been create !

However I know that with the previous code, whenever I will create an instance a new row will be added to the table. Actually with the ID = - 2, I'll get a Identity Insert expcetion, but if I remove it, a new row will be added every time.

I've done a similar thing but the primary key was of type string, therefore I had no problem to seed the first instance with an explicit primary key, and then instantiate the following objects with the same primary key, thus avoiding duplicates.

Here, since the PK is of type int, this column is marked as auto-generated, and this is indeed what I want. But in this specific case, I'd like to be able to use UnknownProduct as a referential data, that I can instantiate directly from C# without having duplicates in the DB. Any idea of how I can achieve this ?

tobiak777
  • 3,175
  • 1
  • 32
  • 44
  • @red3nb What exactly do you mean by `whenever I will create an instance a new row will be added to the table`? With EF you should have complete control over what exactly gets added. – user2697817 May 19 '15 at 10:45
  • Don't build dependencies on keys into your app. Just add unknown as a product like the others and store a constant or app setting that points to it (public const int PRODUCT_UNKNOWN_KEY = 1;) If you really want to control the key value do SET IDENTITY_INSERT OFF in your seed method. – Steve Greene May 19 '15 at 13:10
  • @SteveGreene Thank you,do you know how to set identity insert to OFF in the seed method ? – tobiak777 May 19 '15 at 13:42
  • Thinking about it twice, it's kind of an issue because now I will have to deploy my app twice, the first time to let the seed method run and give some ID to UnknownProduct, and the second time to update the constant you talk about with this ID after I manually look it up in the UP. And finally I need to remove this code my seed method. I'd like a cleaner solution if one exists – tobiak777 May 19 '15 at 13:48
  • Shouldn't need to do that. Code your seed method to check for existance before updating (if (!context.Table.Any())...) or you could use AddOrUpdate() http://thedatafarm.com/data-access/take-care-with-ef-4-3-addorupdate-method/ Turn IDENTITY_INSERT on so you will know the value you care about (http://stackoverflow.com/questions/24265300/identity-insert-during-seeding-with-entityframework-6-code-first). Now configure a constant in a static class or web.config. – Steve Greene May 19 '15 at 14:25

0 Answers0