. NET CORE 3.1 БАЗА ДАННЫХ Как получить доступ к имени, полученному с помощью внешнего ключа - PullRequest
0 голосов
/ 31 января 2020

Я работаю над проектом, использующим базу данных сначала. NET core 3.1. Когда я получаю доступ к информации столбца идентификатора, полученного с помощью внешнего ключа, он равен нулю.

Пользователь Модель

public partial class User
{
    public User()
    {
        Article = new HashSet<Article>();
    }

    [Key]
    public int UserId { get; set; }
    [StringLength(50)]
    public string UserName { get; set; }
    [StringLength(50)]
    public string UserSurname { get; set; }
    [StringLength(50)]
    public string Password { get; set; }
    [StringLength(50)]
    public string UserEmail { get; set; }
    public int? RolId { get; set; }

    [ForeignKey(nameof(RolId))]
    [InverseProperty(nameof(Role.User))]
    public virtual Role Rol { get; set; }
    [InverseProperty("User")]
    public virtual ICollection<Article> Article { get; set; }
}
}

Ролевая модель

public partial class Role
    {
        public Role()
        {
            User = new HashSet<User>();
        }

        [Key]
        public int RoleId { get; set; }
        [StringLength(50)]
        public string RoleName { get; set; }

        [InverseProperty("Rol")]
        public virtual ICollection<User> User { get; set; }
    }
}

AdventureContext

 public partial class AdventureContext : DbContext
    {
        public AdventureContext()
        {
        }
        public AdventureContext(DbContextOptions<AdventureContext> options)
            : base(options)
        {
        }
        public virtual DbSet<Article> Article { get; set; }
        public virtual DbSet<Category> Category { get; set; }
        public virtual DbSet<Comment> Comment { get; set; }
        public virtual DbSet<Images> Images { get; set; }
        public virtual DbSet<Role> Role { get; set; }
        public virtual DbSet<User> User { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
               optionsBuilder.UseSqlServer("Server=DESKTOP-Q779BF0\\SQLEXPRESS;Database=cmsData;Trusted_Connection=True;");
            }
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Article>(entity =>
            {
                entity.HasOne(d => d.Category)
                    .WithMany(p => p.Article)
                    .HasForeignKey(d => d.CategoryId)
                    .HasConstraintName("FK_Article_Category");

                entity.HasOne(d => d.Image)
                    .WithMany(p => p.Article)
                    .HasForeignKey(d => d.ImageId)
                    .HasConstraintName("FK_Article_Images");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.Article)
                    .HasForeignKey(d => d.UserId)
                    .HasConstraintName("FK_Article_User");
            });

            modelBuilder.Entity<Comment>(entity =>
            {
                entity.HasOne(d => d.Article)
                    .WithMany(p => p.Comment)
                    .HasForeignKey(d => d.ArticleId)
                    .HasConstraintName("FK_Comment_Article");
            });

            modelBuilder.Entity<User>(entity =>
            {
                entity.HasOne(d => d.Rol)
                    .WithMany(p => p.User)
                    .HasForeignKey(d => d.RolId)
                    .HasConstraintName("FK_User_Role");
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

Просмотр

@ foreach (элемент var в Model) {@ Html .DisplayFor (modelItem => item.UserName) @ Html .DisplayFor (modelItem => item.UserSurname) @ Html .DisplayFor (modelItem => item.Password) @ Html .DisplayFor (modelItem => item.UserEmail) @ Html .DisplayFor (modelItem => item.Rol.RoleName)}

Я хочу получить роль. Почему бы не прийти? [UserIndex List View] [1] [1]: https://i.stack.imgur.com/2f2CZ.png

1 Ответ

0 голосов
/ 05 февраля 2020

Вы должны загрузить связанные объекты в методе действия вашего контроллера. Примерно так:

var list = db.User.Include(u => u.Rol).ToList();

Подробнее о том, как загружать связанные сущности, можно узнать в Документах Microsoft: https://docs.microsoft.com/en-us/ef/core/querying/related-data

...