In MVC (according to the tutorials) the core framework will automatically generate foreign keys for related tables. Example:
public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public int DepartmentID { get; set; } <-----FK to Departments public Department Department { get; set; } public int DepartmentID { get; set; } <-----Primary Key for Departments public string Name { get; set; } public decimal Budget { get; set; } public DateTime StartDate { get; set; } public int? InstructorID { get; set; }
For this to work, do the columns in the two tables need to have identical names? I.E. DepartmentID in both tables.
Or, failing that, how would I get EF to generate the FK when the two columns do NOT have identical names? Example:
Department Table: public Guid Id { get; set; } <-----PK for department table public string DepartmentID { get; set; } public string DepartmentName { get; set; } public Guid? DepartmentManager { get; set; } <-----FK to employee table Employee Table: <-----PK for employee table public Guid ID { get; set; } public string EmployeeID { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; }
How do I get the framework to associate the FK DepartmentManager in Department Table to the PK ID in Employee Table?
NOTE: I'm kinda using FK and navigation property interchangeably here. What I'm really looking for is how to link the two tables within the app.
I think this is the best way to explain it. The code snippet above include all the relevant bits for the two tables/models. The only thing else omitted is the actual cshtml and cshtml.cs page.
I store the value in the EmployeeID - which is the PK - from the Employee Table in the DepartmentManager (Guid) column in the Department Table.
Example: Department is Finance. Department Manager is Joe, Blow. DepartmentManager column in DepartmentTable holds the EmployeeID for Joe Blow from the Employee table.
In SQL I would do this as a LEFT JOIN. However, since I am doing code first, the framework supposedly will make that connection for me.
Thanks, John
https://stackoverflow.com/questions/66846195/id-column-names-in-mvc March 29, 2021 at 05:03AM
没有评论:
发表评论