How to declare single-key fields with EntityFramework?

2

One thing that many are looking for but there is no feature available in versions from EntityFramework to 6 is the use of unique keys ( unique keys ).

Including users asking how to create such a control and the incredible is that answers have come up indicating such a UniqueKey (?) ( Do not allow to write duplicate registrations ) . But such an attribute does not exist.

How to control single fields?

    
asked by anonymous 09.05.2014 / 23:23

1 answer

3

With the version of EntityFramework 6.1 a new attribute, IndexAttribute , has come up, and with it it is possible to make this type of declaration.

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

    
09.05.2014 / 23:23