One-to-one relationship in Entity Framework mvc

0

I have two entities, Service and Contract, their relationship must be one to one. the requirement is simple. how can I achieve this by means of data annotations or fluent api.

the following is the code that I have (Entity Service)

[ForeignKey("Contrato"]    
public string NumeroLinea { get; set; }

public virtual Contrato Contrato { get; set; }

(Contract Entity)

public virtual Servicio Servicio {get; set; }

- > When I do the migration, it generates multiple errors.

  

the following is the error:    Service_Contract_Source:: Multiplicity is not valid in Role 'Service_Contract_Source' in relationship 'Service_Contract'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

    
asked by Drz 23.11.2016 в 19:31
source

1 answer

0

Here both entities need to have Id (A primary key) in order to create the foreign keys, that is:

Contract Entity

public Contrato
{
  [Key]
  public long Id {get; set;}

  //... Otras propiedades aquí ...

  public long IdServicio {get; set;}      

  [ForeignKey("IdServicio")]
  public virtual Servicio Servicio {get; set;}
}

Entity of Service

public Servicio
{
  [Key]
  public long Id {get; set;}

  //... Otras propiedades aquí ...

  public long IdContrato {get; set;}      

  [ForeignKey("IdContrato")]
  public virtual Contrato Contrato {get; set;}
}

Greetings

    
answered by 09.12.2016 в 16:32