2017-04-02 49 views
0

我有兩個表; 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); 
    } 
} 

也許我誤解了,但我想,當我使用正確的命名約定項目屬性將自動無需任何額外的代碼填入?

非常感謝提前!

+0

將'DbSet'屬性標記爲'virtual'。 –

回答

相關問題