[英]How do I get the id of record in foreign key table using another column in that table in ASP.NET MVC?
I am new to ASP.NET MVC. 我是ASP.NET MVC的新手。 Using Entity Framework 6, I am working on a project to store employee skills in a database. 使用Entity Framework 6,我正在从事一个将员工技能存储在数据库中的项目。 The user can enter a new skill into a list of skills. 用户可以将新技能输入技能列表。 I would like to keep track of who added the new skill. 我想跟踪谁增加了这项新技能。 I have a table of all of the employees. 我有一张所有员工的桌子。
These are the models for the two tables. 这些是两个表的模型。
public partial class Skill
{
public int ID { get; set; }
public string Skill { get; set; }
[ScaffoldColumn(false)]
public int LastActionUserID { get; set; }
public virtual Employee Employees { get; set; }
}
public partial class Employee
{
public int ID { get; set; }
public string EmployeeLAN { get; set; }
public int LastActionUserID { get; set; }
public virtual Employee Employees { get; set; }//References itself for LastActionUserID
public virtual ICollection<Skill> Skills{ get; set; } //Omitted in initial question
}
There is a 1 to Many mapping of Employee to Skill. 员工与技能之间存在一对多的对应关系。 I can get the current user's EmployeeLAN but how do I get the id of that Employee record to put into the Skill table automatically when then new skill is created? 我可以获取当前用户的EmployeeLAN,但是在创建新技能时如何获取该Employee记录的ID自动放入Skill表中? Must I convert the table to an enumerable object and use SingleOrDefault or LINQ? 我必须将表转换为可枚举的对象并使用SingleOrDefault或LINQ吗? Or is there an easier way using EF6? 还是有使用EF6的更简单方法? Also, setting this automatically when a new skill is created would be done in the controller, correct? 另外,在创建新技能时将自动在控制器中进行设置,对吗?
You're on the right track and you should continue to use EF6. 您走在正确的道路上,应该继续使用EF6。
The Employee class should have a Skills list. Employee类应具有“技能”列表。 That way you can call myEmployee.Skills and have a list of all the skills available. 这样,您可以调用myEmployee.Skills并获得所有可用技能的列表。
public partial class Employee
{
public int ID { get; set; }
public string EmployeeLAN { get; set; }
public int LastActionUserID { get; set; }
public virtual ICollection<Skill> Skills{ get; set; }
}
Also, setting this automatically when a new skill is created would be done in the controller, correct? 另外,在创建新技能时将自动在控制器中进行设置,对吗?
You'll need to add to the Skills list, call AddOrUpdate() to mark this as changed, then SaveChanges() to persist it to the database. 您需要将其添加到“技能”列表中,调用AddOrUpdate()将其标记为已更改,然后调用SaveChanges()将其持久化到数据库中。
I recommend learning more from the MSDN docs and Julie Learman's Entity Framework videos on Pluralsight 我建议从PSDN上的MSDN文档和Julie Learman的Entity Framework视频中了解更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.