Do not allow to record duplicate registrations

4

I'm developing a system using ASP.Net MVC and Entity Framework.

How do I not allow equal data to be written to a table? For example, do not allow login: x to be registered more than once.

    
asked by anonymous 05.05.2014 / 14:19

5 answers

3

On the other hand, with EntityFramework 6.1 you can use IndexAttribute .

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

An example for a 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; }
    ....
}
    
09.05.2014 / 23:14
2

Your question has become too broad, you need to go into more detail. For example: What type of database are you using?

Log control is done directly in the database and you should treat this rule directly in it.

The database has a property called PRIMARY KEY , I believe you have heard of it. It does the control of the records not allowing you to duplicate a certain field, it follows link with examples in several databases languages of how to apply PK .

link


EXAMPLE: MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Persons
ADD PRIMARY KEY (CAMPO_A_SER_APLICADO)
    
05.05.2014 / 14:25
2

You can do it in several ways. The @andervoc solution in the model is perfect. I would just add this command to the database, this would give you greater security:

ALTER TABLE TABELA ADD CONSTRAINT NOMEDATABELA_UK01 UNIQUE (CAMPOS);

Practical example:

link

With this the bank would give the error:

Violation of UNIQUE KEY constraint 'USUARIO_UK01'. Cannot insert duplicate key in object 'dbo.USUARIO'. The duplicate key value is (Maria).: insert into USUARIO values ('Maria')
    
05.05.2014 / 15:47
2

One way to do this, for a User class, for example, would be to place the Login field as Primary Key .

public class User 
{
    [Key]
    public string Login { get; set; }
    public string Password { get; set; }
    ...
}

The EntityFramework does not have the UniqueKey attribute. You could create it.

Creating the UniqueKey attribute would involve creating a validation for your back-end and at least creating a mechanism to insert in> uniques .

O Attribute:

public class UniqueKeyAttribute : Attribute
{ 
    ... // incluir a validação para o back-end
}

Creating the uniques , compound, in the database:

ATTENTION : I do not guarantee this way to create uniques as generic for all databases.

public class DatabaseUniqueKeyConfiguration
{
    // Cria as Unique keys no banco de dados
    public static void CreateUniqueKeys(Context context)
    {
        //Fetch all the father class's public properties 
        var masterProperties = typeof(DbContext).GetProperties().Select(x => x.Name).ToList();

        //Percorre cada DBSet<> do DbContext
        foreach (var item in context.GetType().GetProperties().Where(p => masterProperties.IndexOf(p.Name) < 0).Select(x => x))
        {
            //busca o tipo de "T" 
            Type entityType = item.PropertyType.GetGenericArguments()[0];

            // Cria as chaves únicas
            var fields = from f in entityType.GetProperties()
                         where f.GetCustomAttributes(typeof(Domain.Attributes.UniqueKeyAttribute), true).Count() > 0
                         select f.Name;

            var uniqueKeys = "";
            foreach (string s in fields)
            {
                if (string.IsNullOrEmpty(uniqueKeys) || string.IsNullOrWhiteSpace(uniqueKeys))
                    uniqueKeys = s;
                else
                    uniqueKeys += ", " + s;
            }

            var tableName = entityType.Name;
            var attr = System.Attribute.GetCustomAttributes(entityType).SingleOrDefault(x=>x.GetType() == typeof(TableAttribute)) as TableAttribute;
            if (attr != null)
                tableName = attr.Name;

            if (!string.IsNullOrEmpty(uniqueKeys) && !string.IsNullOrWhiteSpace(uniqueKeys))
                context.Database.ExecuteSqlCommand("alter table " + tableName + " add unique(" + uniqueKeys + ")");
        }
    }
}

Then you could create your class by adding the property UniqueKey .

public class User
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [UniqueKey]
    public string Login
}

Well, so you would have the desired attribute validating on the backend and could create a valid front end / strong> querying for AJAX.

    
06.05.2014 / 04:17
0

In your data class, using code first, you can include the "Key" attribute above the property. So you indicate that that field is a primary key.

[Key, MaxLength(36), MinLength(36)]
public string CampoId { get; set; }
    
20.05.2014 / 22:00