One-to-one relashionship Entity Framework and .NET

Viewed 76

I am creating a relationship between my classes using code first. The integration happens with MySql, however, after migrating it consider the relationship as one-to-many when I check my workbench ERD.

How can I make a relashionship one-to-one using the classes mentioned below?

Here is my code:

public class About  
{
    [ForeignKey("User")]
    public int Userid { get; set; }
    public int id { get; set; }
    public string about_file { get; set; }
    public string about_desc { get; set; }
    public virtual User User { get; set; }
}

public class User 
{
    [Key]
    public int id { get; set; }
    public string login { get; set; }
    public string password { get; set; }
    public virtual About About { get; set; }
    public ICollection<Offers> Offers { get; set; } = new List<Offers>();
    public ICollection<Portfolio> Portifolios { get; set; } = new List<Portfolio>();
}

Microsoft.EntityFrameworkCore Version: {5.0.7}

Image from my ERD generated by workbench

1 Answers

It is a one-to-one relationship by convention only. Having a navigation property instead of a collection, ensures that only one child entity can be related to one parent from Entity Framework's perspective. But on the database level, there is nothing that prevents the creation of multiple child entities.

If you want to enforce it on the database level, add a UNIQUE constraint to the foreign key on the child entity, or make the primary keys on both entities identical and make that the foreign key instead.

Related