E
E
egorggegor2020-08-03 21:31:27
C++ / C#
egorggegor, 2020-08-03 21:31:27

How to organize a one-to-one communication?

Hi, does anyone have an example of how a one-to-one relationship should be correctly set in an entity framework via data annotations. Everything that I tried is very doubtful, in almost all examples the dependent object does not have its own identifier, it turns out that the dependent object is tied to only one specific object.
How can you write correctly?
Below is the code that clearly demonstrates the essence of the problem.

public class User
{
    public int Id { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
 
    public UserProfile Profile { get; set; }
}
 
public class UserProfile
{
    [Key]
    [ForeignKey("User")]
    public int Id { get; set; }
 
    public string Name { get; set; }
    public int Age { get; set; }
 
    public User User { get; set; }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yuopi, 2020-08-03
@yuopi

That should work.)

public class User
{
    public int Id { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
 
    public virtual UserProfile Profile { get; set; }
}
 
public class UserProfile
{
    public int Id { get; set; }
 
    public string Name { get; set; }
    public int Age { get; set; }

    [ForeignKey("UserId")]
    public virtual User User { get; set; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question