2011-11-30 76 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