One-To-One relationship with EF?

Asked

Viewed 56 times

1

I’m trying to create a relationship OneToOne with EF6. In my scheme I have a User class and a Plan and the relationship would be 1 User has 1 Plan, however, this relationship is done when the User pays the Plan that then do the relationship.

I used the HasOptional<Plano>(u => u.plano) to do the mapping on the User side, except the information in the database usually with the relationship, the problem is that when I do a search the Plan does not return together with the User and I do not know why it happens.

How to solve this ?

public class Usuario
{
    public long id { get; set; }
    public Plano plano { get; set; }
}
public class Plano
{
    public int id { get; set; }
}

Mapping:

public class UsuarioMap : EntityTypeConfiguration<Usuario>
{
    public UsuarioMap()
    {
        this.ToTable("Usuarios");
        this.HasKey<long>(u => u.id);
    
        this.HasOptional<Plano>(u => u.plano);
    }
}

In the code below, the property Plano is void.

Usuario usuario = context.usuarios.Where(u => u.id == usuarioSession.id).FirstOrDefault();

1 answer

2


You must use the method Include(x => x.NomeDaSuaEntidade) together with the context call when returning entities related to your model.

But in addition you must also put a property of Foreign Key (foreign key) that allows the bank to identify which field relates the two entities, that is their models should look like this:

public class Usuario{
    public long id                  { get; set; }
    public virtual Plano plano      { get; set; }

public class Plano{
    [ForeignKey("Usuario")]
    public long id                   { get; set; }

After configuring your entities correctly, you can make the following call to pick up Users and Plans related to them.

Usuario usuario = context.usuarios.Include(x => x.plano).Where(u => u.id == usuarioSession.id).FirstOrDefault();
  • instead of Include(x => x.plano) I used the Include("Plano") and it worked. Thank you.

Browser other questions tagged

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