Association 1 to 1 Entity

Asked

Viewed 266 times

2

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

Academia class:

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

Address class

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

When I do the Enable-Migration I receive 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 Relationship Fluent API or data Annotations.

From what I understand, Entity doesn’t know how to define who is the main one between the two classes

2 answers

1

from what I understand, Entity doesn’t know how to define who is the main one between the two classes.

Exactly. And he needs to know. The "main" is the model that can exist independent of the other exist or not, or else, the one that will be inserted first. In the example, logically, an academy could exist without an address, but you can’t have an address without an academy. So, Academia is the main part of this relationship.

How to do this:

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

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

    [Required]
    public virtual Academia Academia { get; set; }
}

1

When it is a 1-to-1 relationship, one of the tips needs to be the main one and the other the dependent one. The main tip will be inserted first into the seat and can exist without the other. The dependent must be inserted after the main one is inserted as it contains a foreign key to 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; }
}

Browser other questions tagged

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