Почему не работают виртуальные поля у моделей?

Модель пользователя:
public class User
    {
        [Key]
        public int Id { get; set; }
        public string Email { get; set; }
        public string  FirstName{ get; set; }
        public string LastName { get; set; }
        public string Password { get; set; }
        public int CreatedAt { get; set; }
        public virtual ICollection<Video> Videos { get; set; }
    }


Модель видео:
public class Video
    {
        [Key]
        public int Id { get; set; }
        public int UserID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string File { get; set; }
        public string Hash { get; set; }
        public int CreatedAt { get; set; }
        public int Views { get; set; }
        public virtual User User { get; set; }
    }


При попытке обратиться к виртуальному полю:
@foreach (Video item in Model)
{
        <a href="">@item.User.FirstName</a>
}


Результат:
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An error occurred while executing the command definition. See the inner exception for details.
  • Вопрос задан
  • 237 просмотров
Решения вопроса 1
@SZolotov
Asp.net core, MAUI,WPF,Qt, Avalonia
А как вы получаете данные из базы? По умолчанию EF не поддтягивает данные из связанных таблиц.
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
DarkRaven
@DarkRaven
разработка программного обеспечения
Вы где-то IQueryable разматываете и и внутри этого процесса вы еще раз идете в DbContext за чем-то.
Сложно точнее сказать.
Посмотрите, где с IQueryable коллекциями работаете.
Ответ написан
Комментировать
@VitGun
public class Video
    {
        [Key]
        public int Id { get; set; }
        [ForeignKey("User")]
        public int UserID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string File { get; set; }
        public string Hash { get; set; }
        public int CreatedAt { get; set; }
        public int Views { get; set; }
        public virtual User User { get; set; }
    }


Ну и ключи должны быть на уровне БД созданы.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы