W
W
wkololo_4ever2014-03-14 10:07:29
ASP.NET
wkololo_4ever, 2014-03-14 10:07:29

How to work with dependent tables in EF?

There are 2 models

public class News
    {
        public int NewsID { get; set; }
        public string NewsArticle { get; set; }

        public virtual User User { get; set; }
        public int UserId { get; set; }
    }
   public class User
    {
        public int Id { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }

        public virtual ICollection<News> News { get; set; }
    }

I'm trying to take data about the User from the received News model
@foreach (AuthorizationNew.Models.News News in Model.News)
{
News.NewsArticle 
   Автор @News.User.Email 
}

Gives an error
There is an open DataReader assigned to this Command that needs to be closed first.
How to fix it? And what is its meaning?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AlexP11223, 2014-03-14
@wkololo_4ever

Gives an error
There is an open DataReader assigned to this Command that needs to be closed first.
How to fix it? And what is its meaning?

Burn the Russian studio and put the English one. And then google it:
https://www.google.com/search?q=ef+there+is+alread...
stackoverflow.com/questions/4867602/entity-framewo...

W
wkololo_4ever, 2014-03-14
@wkololo_4ever

@AlexP11223 I found the error description in English, I'm interested in something else, why doesn't lazyloading always work?
Here, for example, I have two other models

public class Section
    {
        public int Id { get; set; }
        public string SectionName { get; set; }
        public int SectionIndex { get; set; }
        public virtual ICollection<Theme> Theme { get; set; }
    }

public class Theme
    {
        public int ThemeId { get; set; }

        [Display(Name = "Название темы")]
        public string ThemeName { get; set; }
  
        public virtual Section Section { get; set; }
        public int SectionId { get; set; }

    }

And pass through the Section model to get Theme
@foreach (AuthorizationNew.Models.Section sc in Model)
{
   sc.SectionName 
        @foreach (AuthorizationNew.Models.Theme th in sc.Theme.OrderByDescending(m => m.ThemeDate).Take(3).ToList())
      {
          th.ThemeName
      }
}

And it works! The question is, what is the difference between what I described in the first post?

W
wkololo_4ever, 2014-03-14
@wkololo_4ever

@AlexP11223 Um, just added ToList() to the pass and it worked

@foreach (AuthorizationNew.Models.News News in Model.News.ToList())
{
News.NewsArticle 
   Автор @News.User.Email 
}

How is that? What is he doing? Loads all the data that should be loaded by lazyloading?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question