D
D
Denis Goncharenko2016-12-12 14:52:06
ASP.NET
Denis Goncharenko, 2016-12-12 14:52:06

Why don't virtual fields work for models?

User Model:

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

Video model:
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; }
    }

When trying to access a virtual field:
@foreach (Video item in Model)
{
        <a href="">@item.User.FirstName</a>
}

Result:
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.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vyacheslav Zolotov, 2016-12-12
@denis79513

How do you get data from the database? By default, EF does not pull data from related tables.

A
Alexander Kuznetsov, 2016-12-12
@DarkRaven

You are unwinding IQueryable somewhere and inside this process you go to DbContext again for something.
It's hard to be more precise.
See where you work with IQueryable collections.

V
VitGun, 2016-12-12
@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; }
    }

Well, the keys must be created at the database level.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question