Selecting from multiple tables in a lambda expression using Entity Framework Core


#1

Hi!

I have two tables; ItemListType and Item.

ItemListType contains a column named Name (name is passed to the method containing the lambda expression)
Item has a column named ItemListTypeId which matches the Id in ItemListType.

So I need to select the row with the correct name from ItemListType and select Item’s with the ListTypeId from Item.
I’ve never worked with Entity Framework or lambda expressions before so I don’t know how to use multiple Include’s (if that is the correct way to do it)

ItemListType

public class ItemListType
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string DisplayName { get; set; }
    public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>();
    public enum ItemListTypes
    {
        Student = 1,
        Work = 2,
        Gamer = 3,
        Other = 4
    }
}

Item

public class Item
{
    public int Id { get; set; }
    public bool Visible { get; set; }
    public string Name { get; set; }
    public string Graphic { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public int OrderBy { get; set; }
    public int ItemTypeId { get; set; }
    public int ItemListTypeId { get; set; }
    public virtual ItemType ItemType { get; set; }
}

This is my lambda expression so far:
ItemListType result = await this.ItemListTypes.Include(i => i.Items).SingleAsync(i => i.Name == name);

In SQL I would do it like this:
SELECT item.* FROM Item item, ItemListType listType WHERE listType.DisplayName = 'student' AND listType.ID = item.ItemListTypeId

But I want to start using Entity Framework instead of sql queries.

Any ideas??


#2

Hello,
I don’t understand what you want because you can access all your items with the items property
IEnumerable<Item> items = this.ItemListTypes.Items;
If that’s what you looking for you may search on WEB (MVA, or other mooc) for a courses about Code first aproch and Entity framework Code first. (http://www.entityframeworktutorial.net/code-first/configure-one-to-many-relationship-in-code-first.aspx)


.NET Foundation Website | Blog | Projects | Code of Conduct