Repeatless attribute (Unique) with Entity Framework?

Asked

Viewed 219 times

3

I’m creating a model with two attributes that can’t be repeated, one GUID and a string.

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

If not, how to do it?

  • Which EF version you are using?

1 answer

2


Whereas 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 at my view should create a Unique Key, as in your example:

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

The second way would be Data Annotation Attribute, is an option but I don’t like it because I work with "POCO" classes, and these attributes polououem the code. But it would look like this.

Supposing your property is called X

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

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

  • Blz! Thank you Rodrigo!!!

  • If the answer answered you, do not forget to accept it by clicking on the V.

  • 1

    You could complete your answer by saying that the solution is for Entity Framework 6 and Core: see link: https://docs.microsoft.com/pt-br/ef/core/modeling/indexes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.