c# – Map associative tables in Entity

Question:

This has already happened. When I use a join table in Entity, these tables usually don't have PK. When that happens, I can't map them. How can I map this type of table?

Answer:

Map manual. 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 that the Entity Framework is mis-mapping its Models schema.

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

Scroll to Top