简体   繁体   中英

Connect to multiple tables or join two tables in ASP.NET MVC C#

Sorry if the title was confusing.

Lets say I have a model called Employee. Employee has a column called Departments. This allows them to view the calendar for that department. But some Employees should be able to view the calendar for multiple departments, and it is different for every employee.

Because there are many different departments, I do not want to have the Employee table filled with a ton of new columns for each department.

I saw something about linking (not sure if that is the right word) two tables. So I made a second model/table called AdditionalDepartments that has the AdditionalDepartmentsId, EmployeeId, and Department.

Say Joe was part of department A but can also view B and C. This is what employee looks like.

EmployeeId | name | Department
-------------------------------
    1      | Joe  |  IT

and the AdditionalDepartments would look like...

AdditionalDepartmentsId | EmployeeId | Department
--------------------------------------------------
        1               |      1     |  HR
        2               |      1     |  Sales

How would I go about combining these? Or is there a better way to store additional department information rather than two tables?

I ask because in my view, when they create or edit an employee, they use the employee database, but I want to be able to set additional departments on these views. The problem with that is you can only use one model per view so I am having difficulties.

Note: I cannot drop the Department from Employee because it is used for a lot more than what the AdditionalDepartments would be used for.

You would want the Employee model to have an IEnumerable<Department> that contains all the Departments that employee is a part of.

On a somewhat unrelated note, if you have the ability to change the table schema at all, you could just drop the Department column in the first table, and make the second table just be a list of departments associated with employees based on the employeeID columns (they would have a foreign key relationship).

Sorry if I misunderstood your question, but unless you are taking one database to be a single model, this should do the trick for you.

Change your first table column to something like OfficialDepartment. In your second table, drop the 'Additional' and just leave it as Departments. Add 'IT' to this table for 'Joe' as well. Then output the SQL using the statement below into a List<Departments> into your model and use as needed.

select A.Departments as [Departments]
from Employees E
join Departments D on E.EmployeeId = D.EmployeeId
where E.EmployeeId = <empId>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM