How to use class interface with a view

Coreysan 1,651 Reputation points
2022-04-18T23:26:19.05+00:00

I'm learning about interfaces in views (MVVM), and wanted to ask about a simple case:

Here's some very basic code:

public interface IInventory {
   public int Id { get; set; }
   public string Name { get; set; }
}

public class Inventory : IInventory {
    public int Id { get; set; }
    public string Name { get; set; }
}

public InventoryViewModel {
   public IEnumerable<Inventory> Inventory { get; set; }
   public PagingInfo PagingInfo { get; set; }
}

Then in the controller:

 IEnumerable<IInventory> all_inventory = from m in mydb.Inventory select m;

So here's my question: when I want to get the inventory into a VM with the PagingInfo,
I start with:

 InventoryViewModel myVM = new InventoryViewModel {
      Inventory = all_inventory.Skip(5),
      PagingInfo = new PagingInfo ........

This won't work because "Inventory" is an IEnumerable listing class instances, but "all_inventory" is an IEnumerable listing interface instances.

I know I'm using it wrong. How would I fix this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,308 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Zhi Lv - MSFT 32,056 Reputation points Microsoft Vendor
    2022-04-19T02:11:14.687+00:00

    Hi @Coreysan ,

     InventoryViewModel myVM = new InventoryViewModel {    
    
           Inventory = all_inventory.Skip(5),  
           PagingInfo = new PagingInfo ........  
    

    Try to modify the code as below:

        InventoryViewModel myVM = new InventoryViewModel  
        {  
            Inventory = all_inventory.Select(c=> new Inventory() { Id = c.Id, Name= c.Name}).Skip(5).ToList(),  
            PagingInfo = new PagingInfo() ...  
        };  
    

    Besides, you can also modify the controller code as below: change the all_inventory data type from IEnumerable<IInventory> to IEnumerable<Inventory>:

    IEnumerable<Inventory> all_inventory = from m in mydb.Inventory select m;  
    

    In this scenario, there is no need to use the select statement when create the InventoryViewModel model instance.

    Finally, please check your view model, it should like this:

    public class InventoryViewModel {  
        public IEnumerable<Inventory> Inventory { get; set; }  
        public PagingInfo PagingInfo { get; set; }  
    }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments