且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架核心中的列表不会填充

更新时间:2022-10-16 10:13:04

我一定错过了关于加载实体的部分。



我向我的DbContext添加了一个GetItemType方法,它加载了关系数据

 public async Task< ItemType> GetItemType(ItemType.ListTypes type)
{
ItemType result = await this.ItemTypes.Include(i => i.Items).SingleAsync(i => i.Id ==(int)type );

返回结果;
}





现在我可以发送一个ListType并获取一个填充的对象。太好了!块引用>

Hi!

I have two classes; Item and ItemType.
Item contains ItemTypeId and ItemType contains a list over Items.

But the Items list never gets populated. Its always 0.

Item:

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



ItemType:

public class ItemType
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>();

    public enum ListTypes
    {
        Student = 1,
        Work = 2,
        Gamer = 3,
        Other = 4
    }
}



and this is the View Component that selects ItemType:

public class ItemListViewComponent : ViewComponent
    {
        private Data.TechDbContext _context;

        public ItemListViewComponent(Data.TechDbContext context)
        {
            _context = context;
        }

        public async Task<IViewComponentResult> InvokeAsync(Models.ItemType.ListTypes type)
        {
            var single = await (from t in _context.ItemTypes where t.Id == (int)type select t).FirstAsync<Models.ItemType>();

            return View(single);
        }
    }



It finds the correct ItemType, but the Items property are always 0. (yes I've checeked theres data in the db)

Any help with this will be highly appreciated! (since its driving me crazy)

What I have tried:

I've tried debugging and different methods of selecting data. Drop the database and repopulated the data.

I must have missed the part about loading entities.

I added a GetItemType method to my DbContext which loads the relational data
public async Task<ItemType> GetItemType(ItemType.ListTypes type)
{
    ItemType result = await this.ItemTypes.Include(i => i.Items).SingleAsync(i => i.Id == (int)type);

    return result;
}



So now I can send in a ListType and get a populated object back. Great!