thompsonrapier
thompsonrapier

Reputation: 165

One-to-one entity framework

I am doing the entity framework code first to set up my database.

I have two classes where their relationships are one-to-one, Lecturer & LoginInfo.

public class Lecturer
    {
        public int LecturerId { get; set; }
        public string FullName { get; set; }

        public int UserId { get; set; }
        public LoginInfo LoginInfo { get; set; }

    }

public class LoginInfo
{
    public int UserId { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public bool ChangePassword { get; set; }

    public Lecturer Lecturer { get; set; }
}

So for my entity framework, I have written this for the one-to-one relationship.

modelBuilder.Entity<Lecturer>()
                .HasOne(input => input.LoginInfo)
                .WithOne(input => input.Lecturer)
                .HasForeignKey<Lecturer>(input => input.UserId);

From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?

Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this:

modelBuilder.Entity<LoginInfo>()
                .HasOne(input => input.Lecturer)
                .WithOne(input => input.LoginInfo)
                .HasForeignKey<LoginInfo>(input => input.LecturerId);

I am just a beginner trying to learn, thanks for helping :).

Upvotes: 1

Views: 80

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205539

From the code above, does it mean that Lecture has one LoginInfo, LoginInfo with one Lecturer and Lecturer has a UserId as a foreign key?

Correct. It also means that LoginInfo is the principal and Lecturer is the dependent end of the relationship. Also since the FK property is not nullable, the relationship is required, i.e. in order to create Lecturer you have to create LoginInfo first, which is not associated with another Lecturer.

Also note that since the UserId is not following the default convention for PK name, you should explicitly configure it as PK of the LoginInfo:

modelBuilder.Entity<LoginInfo>()
    .HasKey(e => e.UserId);

Another question would be, for this one to one relationship, do I have to write another set of code for LoginInfo like this

No. Single relationship requires single configuration and single FK. If you do so, you would be defining a second relationship, which also would create circular dependency between the entity, which should be avoided in general. The first fluent configuration fully defines the desired relationship and is enough to handle loading related data and other CRUD operations.

For more info about terms, relationship types and configuration, see Relationships section of the EF Core documentation.

Upvotes: 2

Related Questions