0

I have a problem with Include() using Entity Framework. I have two models:

public class Project
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [Display(Name = "Project Title")]
        public string Title { get; set; }
        // Some other properties


        public int ProjectPropertyId { get; set; }
        public ProjectProperty ProjectProperty { get; set; } = new ProjectProperty();

    }

and the other table:

public class ProjectProperty
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [Display(Name = "Published")]
        public bool Published { get; set; } = false;
        [Required]
        [Display(Name = "Code Available")]
        public bool CodeAvailable { get; set; } = false;
    }

When I save a new entity with those properties, No problem. When I want to retrieve, here the problem is. I can get the Project list, but it doesn't include the Project property Entity. This is the code to get the list:

public async Task<List<Project>> GetProjects()
        {
            return await _context.Project.Include(p => p.ProjectProperty).ToListAsync();
        }

On the break point I get this:

enter image description here

I can't get that entity with Include() but in the database:

enter image description here

I know I did a stupid mistake, but I can't figure it out. any help will be appreciated thank you.

Kaj
  • 236
  • 4
  • 9
  • 2
    Remove initialization of the reference navigation property `= new ProjectProperty();`. There are many posts on SO explaining why you shouldn't do that, and of course the main reason is that it prevents correct eager/lazy/explicit loading. – Ivan Stoev May 11 '21 at 13:40
  • 1
    I just figured it out right now. Thank you for your help. It work's now. – Kaj May 11 '21 at 13:41
  • @IvanStoev Would you post the comment as an answer so I can mark it as answered. – Kaj May 11 '21 at 13:47
  • 2
    This is one of those posts: [EF codefirst : Should I initialize navigation properties?](https://stackoverflow.com/questions/20757594/ef-codefirst-should-i-initialize-navigation-properties) – Gert Arnold May 11 '21 at 14:03
  • @Gert Thank you, that's my preferred duplicate target for this, I should keep the link somewhere. Even it's been quite time since then, it still applies. – Ivan Stoev May 11 '21 at 14:25
  • @Ivan Sure :) I try to keep it up-to-date every now and then. – Gert Arnold May 11 '21 at 14:29

0 Answers0