This question has already been answered:
- How to get related objects using EF? 2 answers
I am writing a chat authorization using the Entity Framework. Everything has already been written in general for a long time, but when I began to carefully test, I found a bug. The essence of the user looks like this:
public class UserInfo { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Required, MinLength(4), MaxLength(32)] public string Username { get; set; } [Required, MinLength(4), MaxLength(32)] public string Password { get; set; } public long? RoleId { get; set; } [ForeignKey(nameof(RoleId))] public RoleInfo Role { get; set; } public long? BanId { get; set; } [ForeignKey(nameof(BanId))] public BanInfo Ban { get; set; } } So, during registration, UserInfo and RoleInfo are created, Role is assigned, the entity is added to the context list, and SaveChanges is called. But then authorization only works until you stop the server. When restarting the server (and accordingly loading the database), Role disappears from the entity. Although there in the debugger you can see that RoleId is specified, but the essence of Role itself remains null. Why it happens? ForeignKey specified ...
UPD. container code:
public class DbContainer : DbContext { public DbContainer() : base($"name={nameof(DbContainer)}") { } public virtual DbSet<UserInfo> Users { get; set; } public virtual DbSet<RoleInfo> Roles { get; set; } public virtual DbSet<BanInfo> Bans { get; set; } }
Roleproperty? - Bald