Attribute without repeating (unique) with Entity Framework?

3

I'm creating a template with two attributes that can not be repeated, a GUID and a string .

To make string ( not the primary key - primary key is GUID ) a unique field should I use HasIndex(x => x.Atributo).IsUnique(); ?

If not, what do you do?

    
asked by anonymous 22.03.2018 / 03:15

1 answer

2

Considering that you are using'Entity Framework 6 ', you would have two options.

"Fluent Api", which would be the example of your question. That is, yes you can and in my view should create a Unique Key , as in your example:

HasIndex(x=>x.Atributo).IsUnique()

The second form would be Data Annotation Atribute, it's an option but I do not like it because I work with "POCO" classes, and those attributes polouem the code. But it would look like this.

Imagining that your property is called X

[Index( "INDEX_x", IsUnique=true )]
public string x {get;set;}

Editing the answer to inform you that the solution also works for EF Core.

    
22.03.2018 / 13:19