Muhammad Ahmed AbuTalib
Muhammad Ahmed AbuTalib

Reputation: 4322

Entity Framework v5 loading relational data

I have two very simple POCO that i want to connect through a one to many relation

public class Menu
{
    public int MenuId { get; set; }
    public bool IsActive { get; set; }
    public ICollection<MenuMember> MenuMembers { get; set; }
}

public  class MenuMember
{
    public int MenuMemberId { get; set; }
    public int MenuId { get; set; }
    public string  ViewRoute { get; set; }
    public bool IsActive{ get; set; }
}

public  class EFDbContext : DbContext
{
    public DbSet<Page> Pages { get; set; }
    public DbSet<Menu > Menus { get; set; }
    public DbSet<MenuMember> MenuMembers{ get; set; }
}

Now what I have to do is very simple , but I all the resources on the internet are suprisingly so vague (or i am too dumb)

I want to write an lambda expression for

SELECT * 
FROM Menu INNER JOIN MenuMembers 
    ON Menu.MenuId = MenuMembers.MenuId 
WHERE Menu.MenuId = 1

I have used this

IEnumerable<Menu> menu 
    = repository.Menus.Where(x => x.MenuId == menuId);

but when I iterate over it, menu.MenuNumbers stays null. I believe it is some sort of lazyloading issue.

Upvotes: 0

Views: 199

Answers (2)

CodeCaster
CodeCaster

Reputation: 151720

Either Include() the relation manually for eager loading:

Entity Framework Loading Related Entities:

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method.

IEnumerable<Menu> menu = repository.Menus
                                   .Include(m => m.MenuMembers)
                                   .Where(x => x.MenuId == menuId);

Or mark the property as virtual so Entity Framework will lazy-load it:

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

public class Menu
{
    public int MenuId { get; set; }
    public bool IsActive { get; set; }
    public virtual ICollection<MenuMember> MenuMembers { get; set; }
}

And there's a few other options, be sure to check out the documentation.

Upvotes: 1

cuongle
cuongle

Reputation: 75326

You need to declare MenuMembers as virtual

public virtual ICollection<MenuMember> MenuMembers { get; set; }

Upvotes: 1

Related Questions