选中时表不会自动填充项目

时间:2017-04-02 03:54:18

标签: c# entity-framework asp.net-core entity-framework-core

我有两张桌子; ItemType和Item。 Item具有名为ItemTypeId的属性,该属性包含ItemType Id中的值。非常基本的。

的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
    }
}

物品

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; }
}

的DbContext

public class TechDbContext : DbContext
{
    public TechDbContext(DbContextOptions<TechDbContext> options) : base(options)
    {

    }

    public DbSet<ItemType> ItemTypes { get; set; }
    public DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ItemType>().ToTable("ItemType");
        modelBuilder.Entity<Item>().ToTable("Item");
    }
}

最后选择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);
    }
}

也许我误解了,但我想当我使用正确的命名约定时,Items属性会自动填充而不需要任何额外的代码?

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

延迟加载不存在。 https://github.com/aspnet/EntityFramework/issues/3797

 _context.ItemTypes.Include(p => p.Items);