Relationship 1 to 1 with Entity Framework

7

I have 2 entities: Equipamento and Databook . A Equipamento can only have a Databook and a Databook is only a Equipamento . How can I make this relationship with Entity Framework?

Follow the Classes:

public class Equipamento
{
    public int EquipamentoID { get; set; }

    public string Nome { get; set; }
    public string Sigla { get; set; }
    public Databook databook { get; set; }
}

public class Databook
{
    public int DatabookID { get; set; }

    public string Indentificacao { get; set; }   
    public Equipamento equipamento { get; set; }
}
    
asked by anonymous 24.10.2014 / 01:16

2 answers

7

A mapping one to one is done through the relationship where the key of one is also key of the other. So we will have the key field in class Todo being the key of class parte .

public class Todo{
    public virtual Parte ObjParte { get; set; }
}

public class Parte{
    [Key]
    public int TodoID { get; set; }
    public virtual Todo ObjTodo { get; set; }
}

In class Contexto we can do this mapping also with Fluent Api :

public class Contexto {
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Parte>()
            .HasKey(x => x.TodoID)
            .HasRequired(x => x.ObjTodo)
            .WithRequiredDependent(p => p.ObjParte);
    }
}
    
30.10.2014 / 19:13
5

Generally, the relationship is done through Foreign Keys information (the Foreign Keys ).

By annotation with attributes, it would look like this in Equipamento :

public class Equipamento
{
    [Key]
    public int EquipamentoID { get; set; }

    public string Nome { get; set; }
    public string Sigla { get; set; }

    // Conforme comentário do AP, essa propriedade não pode existir, ou o EF se perde.
    //public virtual Databook databook { get; set; } 
}

Note the use of virtual . It is especially recommended when using the Entity Framework with configuration of use of proxies classes. Here, the property of type Databook becomes just a navigation property.

A navigation property only signals to the Entitu Framework that a related record can be found in the indicated entity. In this case, we are indicating that a Equipamento can (or does not) have a Databook .

And thus in Databook :

public class Databook
{       
    [Key]
    public int DatabookID { get; set; }

    [ForeignKey("equipamento")]
    public int EquipamentoID { get; set; }   
    public virtual Equipamento equipamento { get; set; }

    // ou assim:
    // sendo esse caso o necessário para quando se trata de entidades 
    // com chaves compostas.
    //
    //[Key]
    //public int EquipamentoID { get; set; }   
    //[ForeignKey("EequipamentoId")]
    //public virtual Equipamento equipamento { get; set; }

    public string Indentificacao { get; set; }
}
    
24.10.2014 / 04:32