ADO.NET 实体框架 - 复合主键 CRUD

发布于 2024-09-19 11:21:43 字数 640 浏览 4 评论 0原文

我有以下实体 alt text

如您所见,BudgetPost 有一个复合主键,它是实体类别和预算的外键。我的问题是创建 CRUD 的最佳方法是什么?有什么办法可以映射外键吗?简单的插入应该如下所示:

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();

还有其他方法吗?

提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

混浊又暗下来 2024-09-26 11:21:43

利用您的导航属性。

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

newBudget.BudgetPosts.Add(newBudget);

也就是说,利用Entity框架的力量。首先,创建您的加入条目并将预算和类别关联起来。然后将budgetPost 添加到预算中。当您调用 SaveChanges 时,所有内容都应该被写入。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文