D
D
DarkByte20152016-05-19 13:14:44
Database
DarkByte2015, 2016-05-19 13:14:44

Why is the property not saved?

I am writing an authorization for a chat using the Entity Framework. Everything has already been written in general for a long time, but when I began to closely test, I discovered a bug. The user entity 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, when registering, UserInfo and RoleInfo are created, Role is assigned, the entity is added to the context list and SaveChanges is called. But authorization then works only until you stop the server. When the server is restarted (and, accordingly, the database is loaded), the Role disappears from the entity. Although there in the debugger you can see that RoleId is specified, the Role entity itself remains null. Why is this happening? ForeignKey is specified...
At the request of the workers... All 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; }
}

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; }
}

public class BanInfo
{
  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public long Id { get; set; }

  [Required]
  public DateTime EndOfBan { get; set; }

  [MaxLength(64)]
  public string Reason { get; set; }
}

[Flags]
public enum UserRole : byte
{
  User = 1,
  Admin = 2,
  SuperAdmin = 4
};

public class RoleInfo
{
  [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public long Id { get; set; }

  [Required]
  public UserRole RoleValue { get; set; } = UserRole.User;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question