I am very new to Entity Framework, so apologies if its a very bad question, but I could not find a solution that makes sense to me. Although my problem is complex, I will try to simplify it. Let’s say I have two models Company and CompanyAddress.
+--------------------Company---------------------------------------+
| int CompanyId
| string CompanyName
|
| virtual <ICollection>CompanyAddress address // Navigation Property
+-------------------------------------------------------------------+
And,
+--------------------CompanyAddress---------------------------+
| int CompanyAddressId
| string Address
|
| int CompanyAddressId // Foreign Key to Address Table
| virtual CompanyAddress address // Related Navigation Property
+--------------------------------------------------------------+
As it can be seen Company entity can have more than one CompanyAddress. In my ASP.NET MVC project I have also ViewModel.
+--------------------CompanyCreateViewModel----------------+
| Company company
| CompanyAddress address
+---------------------------------------------------------+
These two properties are filled on view and passed to controller without problems. Problem for me starts now. How should I insert these two entities ?
Let’s say I insert Company entity first than grab its primaryKey with select statement and assign this value to CompanyAddress’s foreign key and insert it. However, this does not make sense to me, since I need to make another request for primary key.
How should I insert my entities, what is the best approach ? Sorry for long question, and thanks.
Once you call SaveChanges() for the Company, you have the PrimaryKey in that object. Assign it to the foreign key for CompanyAddress and call SaveChanges() again.