开发者

ADO.NET Entity Framework - Composite primary key CRUD

开发者 https://www.devze.com 2023-01-15 23:29 出处:网络
i have following entities 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 wa

i have following entities

ADO.NET Entity Framework - Composite primary key CRUD

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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消