Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define foreign key relationship in EF Core 2.1

I am using EF Core 2.1 for my DAL. This is how my model looks like

One user can have only one role:

// Role entity - kind of master
public class Role
{
    public int RoleId { get; set; }

    public string RoleName { get; set; }
}

// User entity - every user will have one role
public class User
{
    public int UserId { get; set; }

    public string Email { get; set; }
    public string Password { get; set; }

    public int RoleId { get; set; }
    public bool IsActive { get; set; }
    public DateTime CreatedOn { get; set; }

    public virtual Role Role { get; set; }
}

This is how I was thinking/tried to define the relationship between these two entities:

public void Configure(EntityTypeBuilder<User> builder)
{
    builder.HasKey(x => x.UserId);
    builder.Property(x => x.RoleId).IsRequired(true);
    builder.Property(x => x.CreatedOn).IsRequired(true).HasDefaultValue(DateTime.Now);

    // FK - throwing compile time error 
    builder.HasOne(x => x.Role).WithOne(y => y.RoleId);
}

How do I define this one user one role relation using EF Fluent API?

Thanks.

Attachment:- enter image description here

like image 904
Kgn-web Avatar asked Oct 30 '25 21:10

Kgn-web


1 Answers

Not only in the FK relationship configuration, you also have problem in the default value generation configuration for the CreatedOn column. So write your Entity Configuration as follows:

public void Configure(EntityTypeBuilder<User> builder)
{
    builder.HasKey(u => u.UserId);
    builder.Property(u => u.CreatedOn).IsRequired(true).HasDefaultValueSql("getdate()");

    // FK - configuraiton
    builder.HasOne(u => u.Role).WithMany().HasForeignKey(u => u.RoleId).IsRequired(true);
}
like image 134
TanvirArjel Avatar answered Nov 02 '25 10:11

TanvirArjel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!