Assign Inventory to a Department

DIEGO FELIPE ROMERO VALDES 61 Reputation points
2021-10-20T13:15:42.617+00:00

Hello everyone! I'm building an Inventory System where every Department has their own products list.

I have the Department table with:

PK ID - Name

I have the Inventory table with:

PK ID - Product - Category - Observations - FK DepartmentID

I want to be able to see the products separatly for every department in the system. I mean, if i select the inventory for Department 1, see the product list assigned to Department 1.

In those controllers i just have the CRUD operations. There's no problem with that. What can i do? Thank you everyone in advance.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,385 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,262 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 48,311 Reputation points
    2021-10-20T14:28:01.103+00:00

    It would be useful if you posted your entity objects so we can better understand how you've set it up.

    NOTE: I'm using Product here for your Inventory so you can just adjust the naming to meet your actual structure.

    public class Department
    {
       public int Id { get; set; }
       public string Name { get;set; }
    
       //If you want to be able to get the products by department you could expose it this way but it could be expensive if there are a lot.
       public List<Product> Products { get; set; }
    }
    
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } //Product in DB
        public string Category { get; set; }
        public string Observations { get; set; } //??
    
        public int DepartmentId { get; set; }
        public virtual Department Department { get; set; }
    }
    

    You'll have to set up the relationships and column names. Personally I use the fluent API but you can add attributes. I recommend you get this working first.

    Now to get the products by department you can go either way (depending upon where you put your nav property).

    public IEnumerable<Product> GetProductsByDepartment ( int departmentId )
    {
        //Cleanest to me
        return context.Products.Where(x => x.Department.Id == departmentId);
    }
    
    //Or go the other way and load the products when the department loads (assuming you are not using lazy loading here...)
    public Department GetDepartment ( int departmentId )
    {
       return context.Departments.IncludeChildren(x => x.Products).FirstOrDefault(x => x.Id == departmentId);
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful