Retrieve list from object in Database

2019-08-09 08:01发布

问题:

I want to send a list of names contained in a Database using asp.net

These are my two objects:

public class Shop
{
    public int ID { get; set; }
    public string Country { get; set; }
    public List<Item> Items{ get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I want to set a get controller in order to retrieve a list of items. I did something like this:

 public IEnumerable<Item> Get(int id)
    {

        var items= new List<Item>();
        var shop= new Shop();

        using (var systemDB = new ShopsDB())
        {
                            it = systemDB.Shops.Where(s => s.ID == id).FirstOrDefault<Shop>();
                            items = it.Items;
        }   

            return items;

    }

This return <ArrayOfItem i:nil="true"/>. I want to get the complete list of Items for one shop (e.g. shop with ID=1)

回答1:

This will return you the list

using (var systemDB = new ShopsDB())
    {
                        lab = systemDB.Shops.Where(s => s.ID == id).ToList();
                        items = lab.Items;
    }   


回答2:

I solved modifying the Item object:

public class Shop
{
    public int ID { get; set; }
    public string Country { get; set; }
    public List<Item> Items{ get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ShopID { get; set; }
}

And set a query to select the ShopID