Association 1 to 1 Entity

2

I have a relationship between Address and Academy where 1 address has 1 gym, and 1 gym has 1 address.

Academy Class:

public class Academia
{
    [Key]
    public int AcademiaID { get; set; }
    ...
    //relacionamentos
    public int EnderecoID { get; set; }
    public virtual Endereco Endereco { get; set; }
}

Class Address

public class Endereco
{
    [Key]
    public int EnderecoID { get; set; }
    ...
    public int LocalID { get; set; }
    public virtual Local Local { get; set; }
}

When I do Enable-Migration I get the following message:

  

Unable to determine the main end of an association between the types 'Academia.Models.Endereco' and 'Academia.Models.Academia'. The main end of this association must be explicitly configured using either the fluent relationship API or data annotations.

As I understand it, the entity does not know how to define who is the principal between the two classes

    
asked by anonymous 19.01.2017 / 03:40

2 answers

1
  

As I understand it, the entity does not know how to define who is the principal between the two classes.

Exactly. And he needs to know. The "main" is the model that can exist independently of the other one exists or not, or else, the one that is going to be inserted first. In the example, by logic, an academy could exist without an address, but an address can not exist without a gym. So, Academia is the main part of this relationship.

How to do this :

Marking the parent property as [Required] in the non-parent class.

public class Endereco
{
    [Key]
    public int EnderecoID { get; set; }

    [Required]
    public virtual Academia Academia { get; set; }
}
    
19.01.2017 / 11:19
1

When it is a 1 to 1 relationship, one end must be the primary and the other dependent. The main tip will be inserted first into the seat and can exist without the other. The dependent one must be inserted after the main one is inserted, because it contains a foreign key for the main one.

It can be solved this way:

public class Endereco
{
    [Key]
    public int EnderecoID { get; set; }

    [ForeignKey("AcademiaId")]
    public virtual Academia Academia { get; set; }
}
    
19.01.2017 / 11:24