Doubt with relationships N to N or 1 to N

-2

Given the following scenario. I have 1 user table and 1 login table, for example. I need to create my domain class that maps these DB entities. In the login table, I get the user ID. What does this relationship look like in my model?

[Table("Usuario")]
    public class Usuario
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int IdUsuario { get; set; }
        public string NMUsuario { get; set; }
        public string Senha { get; set; }
    }

[Table("Login")]
    public class Login
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int IdLogin { get; set; }
        public DateTime DtLogin { get; set; }
        public virtual ICollection<Usuario> Usuarios { get; set; }?????????
    }

Is that what I put in a Collection? And in the user table, just a virtual UserID?

    
asked by anonymous 16.08.2017 / 14:35

2 answers

3

Using your code above, and understanding that you are using Entity Framework Code First. Just fix your code, also understanding that you want to keep a log of all users' logins, if it logs in the system will generate a log.

public class Usuario
{
    [Key]
    public int Id { get; set; } //Vai ser autoincrement, padrão do entity
    public string NMUsuario { get; set; }
    public string Senha { get; set; }
    public virtual ICollection<Login> Logins { get; set; } //Navigation para ja pegar os registros da tabela login ao consultar os usuarios.
}

public class Login
{
    [Key]
    public int Id { get; set; } //Sequencial somente para efeito de key
    public DateTime DtLogin { get; set; }
    public virtual Usuario Usuario { get; set; } //Aqui se faz a referencia
}

Remembering that you also have to add the two tables in the Context.

    
16.08.2017 / 14:45
2

No, you do not need to use Collection . This will cause the ratio of Login to Usuarios to be 1-N.

The relationship must be 1-1, so you only need a property that represents a Usuario within a Login .

[Table("Login")]
public class Login
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdLogin { get; set; }
    public DateTime DtLogin { get; set; }
    public virtual Usuario Usuario { get; set; }
}
    
16.08.2017 / 14:44