Map associative tables in the Entity

Asked

Viewed 1,261 times

3

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

  • What do you mean, you are creating Table without PK, in relational database? What is the logic in doing this? And remembering the PK mapped in the ORM, it doesn’t necessarily need to be a PK in the database, it should only be a unique identifier. Although it is not a good practice. Explain better your context of creating a table this way?

  • In reality, they are associative tables, that is, intermediate tables when N2N is present. Normally you don’t have PK, only FK’s in these tables and my Entity didn’t map.

  • Two tables were missing. One of them, which I call Usuario_cargo, has two FK’s, which are: Idusuario and Idcargo, only these two fields. This table has not been mapped.

  • 1

    Actually in this case, you created an Nxn relationship between User and Cargo right? Where a User can hold multiple positions and the same position can belong to multiple Users. OK? So if there is nothing to be added in the relation Cargo X User, it is not necessary to explicitly map this relationship, because the User and Position itself already inform what is necessary for the ORM to already recognize this table as a relation between the two. But if you really want to map this relationship table for any reason, you should consider using Composite Key, which would be Idusuario and Idcargo.

  • You need to have a PK to map, even because, it is good practice for Database to have a PK for all tables, even associative tables - it may be required for agility.

1 answer

2


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 mismapping its Models.

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

Browser other questions tagged

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