Map associative tables in Entity

3

This has already happened. When I use an associative table in Entity, these tables generally do not have PK. When this occurs, I can not map them. How can I map this type of table?

    
asked by anonymous 15.08.2014 / 14:46

1 answer

2

Map manually. For example:

public class Usuario 
{
    [Key]
    public int UsuarioId {get;set;}

    [Required]
    public String Nome {get;set;}
    ...
    public virtual ICollection<UsuarioCargo> UsuarioCargos {get;set;}
}

public class Cargo 
{
    [Key]
    public int CargoId {get;set;}

    [Required]
    public String Nome {get;set;}
    ...
    public virtual ICollection<UsuarioCargo> UsuarioCargos {get;set;}
}

public class UsuarioCargo
{
    [Key]
    public int UsuarioCargoId { get; set; }
    [Index("IUQ_UsuarioCargo_UsuarioId_CargoId", IsUnique = true, Order = 1)]
    public int UsuarioId { get; set; }
    [Index("IUQ_UsuarioCargo_UsuarioId_CargoId", IsUnique = true, Order = 2)]
    public int CargoId  { get; set; }

    public virtual Usuario Usuario {get;set;}
    public virtual Cargo Cargo {get;set;}
}

This removes the uncertainty of the Entity Framework from mapping its schema of Models wrong.

[Index] , introduced in this form from the Entity Framework 6.1.0, guarantees the uniqueness of the associative register. Additional validations may be required in the application to avoid extraneous errors of key duplication for the user.

    
15.08.2014 / 21:10