How to declare unique key fields with Entityframework?

Asked

Viewed 82 times

2

Something that many seek but that there is no feature available in the versions of EntityFramework until the 6 is the use of unique keys (Unique Keys).

There were even users asking how to create such a control and the amazing thing is that responses came up indicating such a UniqueKey (??) (Do not allow saving duplicate records).
But there is no such attribute.

How to control unique fields?

1 answer

3


With the version of EntityFramework 6.1 came a new attribute, the IndexAttribute, and with it it is possible to make this kind of statement.

Example:

public abstract class User
{
    [Required]
    [StringLength(50)]
    [Index("IX_User_Login", IsUnique = true)]
    public string Login { get; set; }
    ....
}

An example for index/composite key:

public abstract class User
{
    [Required]
    [Index("IX_User_Empresa", 1, IsUnique = true)]
    public int EmpresaId { get; set; }

    [Required]
    [StringLength(50)]
    [Index("IX_User_Empresa", 2, IsUnique = true)]
    public string Login { get; set; }
    ....
}

Reference: MSDN

Browser other questions tagged

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