简体   繁体   English

DbContext中的一对多映射模型

[英]One to Many mapping models inside DbContext

Currently I am new to MVC and practicing with some demo applications. 目前,我是MVC的新手,正在尝试一些演示应用程序。

I have 2 models. 我有2个模型。

Employee - (with data members employeeId,name,gender,city,deptId) Department - (with data members id,name,Collection employees ) 雇员-(具有数据成员employeeId,名称,性别,城市,deptId)部门-(具有数据成员id,名称,集合雇员)

I have put these two classes inside a context class inheriting from DbContext. 我将这两个类放在从DbContext继承的上下文类中。

Problem is when I try to get employee data based on deptId , it throws error that department_Id column is not defined. 问题是,当我尝试获取基于deptId的员工数据时,会引发未定义department_Id列的错误。 If I remove the employees data member from Department then everything works fine. 如果我从Department删除employee数据成员,则一切正常。 What exactly is happening here, why is it automatically adding a column, and how to tackle it? 这里到底发生了什么,为什么它会自动添加一个列,以及如何处理它?

Don't add deptId property to your Employee class. 不要将deptId属性添加到您的Employee类。 Just add a navigation property like this: 只需添加如下navigation property

public virtual Department Department { get; set; }

And your Department class: 和您的部门班级:

public virtual ICollection<Employee> Employees { get; set; }

Then Entity Framework will create all necessary relationships automatically for you. 然后,实体框架将自动为您创建所有必要的关系。

For more informatin about Navigation Properties take a look at here: http://msdn.microsoft.com/en-us/data/jj713564.aspx 有关导航属性的更多信息,请参见此处: http : //msdn.microsoft.com/zh-cn/data/jj713564.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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