Reputation: 55
I have these lines of code in the DBcontext class. Can someone explain to me what it does? Does it populate User_roles? But if it does should not it be already inside public DbSet<User_Role> User_Roles. Or does it populate nav properties of Role and user?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User_Role>()
.HasOne(x => x.Role)
.WithMany(y => y.UserRoles)
.HasForeignKey(x => x.RoleId);
modelBuilder.Entity<User_Role>()
.HasOne(x => x.User)
.WithMany(y => y.UserRoles)
.HasForeignKey(x => x.UserId);
}
User class
public class User
{
public Guid Id { get; set; }
public string Username { get; set; }
public string EmailAddress { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public List<string> Roles { get; set; }
//nav propery
public List<User_Role> UserRoles { get; set; }
}
Role class
public class Role
{
public Guid Id { get; set; }
public string Name { get; set; }
//nav property
public List<User_Role> UserRoles { get; set; }
}
User_role class
public class User_Role
{
public Guid Id { get; set; }
public Guid UserId { get; set; }
public User User { get; set; }
public Guid RoleId { get; set; }
public Role Role { get; set; }
}
Upvotes: 1
Views: 1133
Reputation: 1039
It doesn't populate anything in terms of data, assuming that's what you're asking. All that does is configure one-to-many relationships between User_Role
and Role
, and User_Role
and User
. This will create your FK constraints in the database when you run migrations and configures your navigation properties.
Recommended reading here: https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key
Upvotes: 3