Search code examples
entity-framework-5entity-relationship

Entity Framework 5 - Create realationships between entities before inserting to Db


I`m learning now EF 5 and I have some issue.

I have 2 different entities:

MainCategory which contains the next fields: mainCatID (primary key), categoryName

and SubCategory which connected to MainCategory by mainCatID: mainCatID (Foreign key) (called MainCategory), subCatID (primary key), categoryName

I`m trying to do the next thing: 1. create main category 2. create under this main category 3 subCategories. 3 execute saveChanges method in order apply those changes into DB

With section 1 I don`t have a problem, when I am trying to create subCategories I am not sure how to apply the relationship between the new main category to his new children subCategories.

While creating the subCategories I need to assign to each subCategory.MainCategory it "father" main category (make the connection between the keys) but this main category does not exists yet in Db (because I want to use saveChanges() just when I finish execute sections 1 and 2) so how can I "tell" to those subCategories "Hi, This is your father, He not exists yet on DB but he will be"? or in other words how can I implement the relationship without firstly adding the father do DB?

Thanks, Ofir


Solution

  • My problem was that I tried to set the relationship by primitive Ids and now I understand that the relationship must be created with object.

    In my example above, If I want create relationship between MainCategory to SubCategory I need take the following steps:

    1. Create mainCategory (will called mainC) object.
    2. Create subCategory (will called subC) object.
    3. Set subC.mainCategory = mainC;

    Thanks to Gert Arnold.