Second unique column using Entity Framework

entity-framework entity-framework-6


I am using EF6 and in my customer table I like to have a column that is of type GUID and is unique. Doesn't have to be a primary. What I want to use this for, is to allow users to unsubscribe from emails. So I though every customer has a GUID under say UnsubscribeEmailGuid column and I send this in a form of a link, when they click it, I can figure out which customer it is, and set their preference to unsubscribe.

Now how can I using EF, define this column and make sure it has some value when a customer is created. I sort of tried:

    public Guid UnsubscribeEmailGuid{ get; set; }


        Property(c => c.UnsubscribeEmailGuid)
            .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute {IsUnique = true}));

But it creates the customer with Guid 00000000-0000-0000-0000-000000000000.

I am pretty sure I have to do something to the above setter property but my brain has stopped working!

Can someone please give me a nudge? Or maybe I am completely on the wrong track?


9/11/2018 1:51:52 PM

Accepted Answer

try with this example, you have to initialize the object, for example i have the user class, and the property type GUID, so:

[Table( "users" )]
public class user{
    [Index(IsUnique = true)]
    public Guid UnsubscribeEmailGuid{ get; set; }

    public user(){
        this.UnsubscribeEmailGuid = new Guid();

then, when you create a new entity of user, the constructor asign a value in UnsubscribeEmailGuid property. aditional to this you can use a DataAnotation for unique index.

9/11/2018 3:02:39 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow