我假设你在使用实体框架给你的代码提供。你必须让你的两个实体之间的关系,并让EF您处理该问题:当您创建的实体
public class Employee {
public int EmployeeId { get; set; }
public virtual Address Address { get; set; }
}
public class Address {
public int AddressId { get; set; }
public int EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
}
现在:
// create a new Employee
Employee employee = new Employee();
// create a new Address
Address address = new Address();
// associate the address with the new employee
employee.Address = address;
// add the employee to the data context
db.employee.AddObject(employee);
// when you call save changes, since your Address is attached to your
// employee, it will get added for you and you don't have to add it to the
// context yourself. Entity Framework will save the Employee, get the ID
// from this table and then add a new Address record using the ID that was
// just inserted.
db.SaveChanges();
这将增加两个对象,并添加外键您。
编辑
这是一个代码第一个例子。如果您首先使用设计器使用数据库,则只需使用设计器设置关系即可。在这种情况下,添加员工的代码不应改变。
你在做代码首先研究与开发?还是你依靠EDMX文件?如果你能提供一些关于你的EF方法的细节,这将有所帮助。 –
你测试过了吗?如果您使用的是EF,则应该只能将empmodel添加到db.employee,然后SaveChanges()。 EF将为您处理创建地址记录。 – Maess
@Maess只有在EF中设置关系的时候:) – Dismissile