Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a rather unique problem so I thought I'd ask here:

I need to put together a Code First model where the user has 2 ID fields, one unique (identifying each user separately), and one which won't be unique for each user (used for grouping purposes).

How do I go about getting a field in there that sometimes gets its value from the database (unique one) and sometimes is set by my code (when I am using it for grouping) ?

Are there any annotations that can help so when I assign a value, that's the one used, and when I don't assign anything, it gets a new ID automatically?

share|improve this question
    
So you will want a primary id, which will be the unique one. This one will auto create whenever you add something to your database. Then the other id you want, (group_id), is the only one you will need to set. You can set your database to auto set the group_id to 1 (default value) if you don't supply it. –  Bobo May 21 at 22:49
    
My question is: Can I somehow get a unique group_id when I don't supply a value for it, and have whatever value I want in there other times? –  Ivan May 21 at 22:57
    
Hmm... I don't know of any way to do this in the database itself, but maybe where you are accessing it, you could keep a list of all the group_ids you already have. So when you want a unique one, just add one to the largest one you have, and use that? –  Bobo May 21 at 23:13
    
That's not possible in my case, but introducing a new entity (group) should solve this issue. I am testing right now. Thanks for your help, Bobo! –  Ivan May 21 at 23:22
    
You could create a trigger on that table. If nothing (NULL) is inserted into the field, generate something. –  ElectricLlama May 22 at 1:50
add comment

1 Answer

up vote 1 down vote accepted

The only way to do this and have the DB generate the value is to use a trigger. Since this is a code-first project you might not want to do that.

The best solution, IMHO, would be to make the GroupId a GUID and then set it to Guid.NewGuid() in the data object constructor. That way it always has a unique value by default and if you set the property it will use your supplied value instead. You get uniqueness by default and grouping when you want it. Since it's maintained in code you don't have to worry about maintaining a trigger somewhere else.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.