2011-11-30 81 views
1

我正在使用c#MVC我试图在2个表中创建2个新记录 - 雇员和地址表。 我至今以下几点:MVC控制器创建新记录

db.employee.AddObject(empmodel.employee); 
    db.address.AddObject(empmodel.address); 
    db.SaveChanges(); 

当员工记录被创建,它创建的自动生成一个记录的EmpID。我需要获得该EmpID并使用该EmpID在地址表中创建一条新记录,因为两个表之间存在主外键关系。

我不确定如何从employee表中获取EmpID,然后为地址表创建新记录。我想我可以在AddObject之后得到它,但它没有创建员工记录。

+0

你在做代码首先研究与开发?还是你依靠EDMX文件?如果你能提供一些关于你的EF方法的细节,这将有所帮助。 –

+0

你测试过了吗?如果您使用的是EF,则应该只能将empmodel添加到db.employee,然后SaveChanges()。 EF将为您处理创建地址记录。 – Maess

+0

@Maess只有在EF中设置关系的时候:) – Dismissile

回答

1

我知道你不应该只是给出反馈,但在这种情况下,这个答案是正确的,没有必要走得更远。如果您使用数据库表创建模型,只要该数据库表具有ID字段即可。它将为您创建get/set方法。在我的,它甚至创建了一个更复杂的get/set方法可能是因为我的ID字段的名称是ProdID。但是您可以扩展model.cs文件(在您从数据库创建模型之后),并查看这些人员正在讨论的get/set方法。在这种情况下,你使用的是GUID你可以使用

card.Guid = Guid.NewGuid(); 

NewGuid()方法在控制器创建功能。

3

我假设你在使用实体框架给你的代码提供。你必须让你的两个实体之间的关系,并让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(); 

这将增加两个对象,并添加外键您。

编辑

这是一个代码第一个例子。如果您首先使用设计器使用数据库,则只需使用设计器设置关系即可。在这种情况下,添加员工的代码不应改变。

+0

我在做db.employee.AddObject(empmodel.employee); db.address.AddObject(empmodel.address);因为我需要在一个镜头中创建2个独立表格中的2条记录。如何从第一个获得EmpID进入第二个? –

+1

请阅读我的答案。如果建立关系,则不必手动添加子对象。它会被添加到你的数据库中。 – Dismissile