views:

52

answers:

1

Hi all

i have following entities alt text

as you see BudgetPost has a composite primary key which is a foreign keys to entities Category and Budget. My question is what is the best way to make CRUD? Is there any way to mapp the foreign keys? The simple insert should look like this:

Budget newBudget = new Budget();
                newBudget.BudgetName = textBox1.Text;
                newBudget.FromDate = dateTimePicker1.Value;
                newBudget.ToDate = dateTimePicker2.Value;

                newBudget.BudgetPosts.Add(new BudgetPost { FKBudgetID = newBudget.BudgetID, FKCategoryID = 21, BudgetAmount = 700 });
                db.AddToBudgets(newBudget);
                db.SaveChanges();

Is there any other way?

Thanks in advance!

+1  A: 

Make use of your navigation properties.

BudgetPost newBudgetPost = new BudgetPost();
newBudgetPost.Budget = newBudget;
newBudgetPost.Category = newCategory;    //loaded somewhere, or created on the fly

newBudget.BudgetPosts.Add(newBudget);

That is to say, make use of the power of the Entity framework. First, create your join entry and associate the Budget and Category there. Then add the budgetPost to the budget. All should get written when you call SaveChanges.

villecoder
Thanks for your answer
ilkin