一对多关系将外键保存为asp.net中的NULL

时间:2012-04-16 13:09:27

标签: c# .net entity-framework-4 foreign-keys

我正在尝试在.net 3.5中的实体框架中定义我的两个表之间的一对多关系。

城市表

CityId
CityName

员工表

 EmployeeId
 EmployeeName
 RegistrationDate
 FK_CityID

我正在尝试在Employee中插入所有数据完全插入数据,但 FK_CityID为instred NULL

插入按钮单击代码        DateTime dt = new DateTime(2008,12,12);

    EmployeeService es = new EmployeeService();
    CityService cs = new CityService();
    Payroll.Entities.Employee e1 = new Payroll.Entities.Employee();

    Payroll.Entities.City city1 = cs.SelectCity(Convert.ToInt32(cmbCity.SelectedItem.Value));

    e1.FK_CityID = city1;
    e1 = Payroll.Entities.Employee.CreateEmployee(0, "Archana",dt);
    es.AddEmpoyee(e1);

e1.City 我传递的是 city1 (城市的对象)的整个对象,它正在完美地通过但在数据库中它将保存NULL < /强>

MyService Class

public string AddEmpoyee(Payroll.Entities.Employee e1)
        {
            //DAO
            Payroll_DAO payrollDAO = new Payroll_DAO();
            payrollDAO.AddToEmployee(e1);
            payrollDAO.SaveChanges();
            return "SUCCESS";
        }

我没有得到我错的地方......

1 个答案:

答案 0 :(得分:0)

嗨,我得到了解决方案..

Payroll.Entities.City city1 = new Payroll.Entities.City();
city1 = cs.SelectCity(Convert.ToInt64(cmbCity.SelectedItem.Value));

e1.EmployeeName = "Archana";
e1.RegistrationDate= dt;
e1.FK_CityID = city1;

es.AddEmpoyee(e1);