处理多对多 - 实体框架
我正在构建一个 MVC 应用程序作为学习项目。我有一张包含收款人的表和一张包含类别的表。某些收款人可以进行某些类别的交易。例如,收款人 A 可以向类别 A、B 和 C 付款。收款人 B 可以向类别 B、C 和 D 付款。
因此,我有一个 PayeeCategory 链接表,其中包含 PayeeId 和 CategoryId。
因此,查看收款人可以进行交易的类别,这是一个简单的 Select from PayeeCategory where PayeeId = this.PayeeId 的操作。我加入类别表以获取类别名称。
在视图中,当我编辑收款人时,我需要显示所有类别的列表,并允许用户选择或取消选择当前收款人关联的类别。
因此,在我的 ViewModel 中,我有一个categorySelectableItems 列表,其中可能包含 CategoryId、DisplayName 和 Selected 布尔字段。为了获取数据,我需要从类别中选择,LEFT JOIN PayeeCategory,并且当 PayeeCategoryId 为空时,将 Selected 设置为 false,否则为 true。
我该如何在单个 Linq 语句中做到这一点?
那么,当数据回来时...我该如何保存数据呢?我是否必须删除所有关系,然后根据 List<> 重新添加它们?我拿回的价值观?
希望有人能指导我。
I have an MVC app I am building as a learning project. I have a table with Payees, and a table with Categories. Certain Payees can make transactions of certain categories. For example, Payee A can make payments to Categories A, B and C. Payee B can maybe payments to categories B, C and D.
So, I have a PayeeCategory linking table, with a PayeeId and a CategoryId.
So see the categories the payee can make transactions against, it's a simple Select from PayeeCategory where PayeeId = this.PayeeId. And I join to the Category table to get the category names.
In the view, when I edit a Payee, I need to display a list of all categories, and and allow the user to select or unselect the categories that the current Payee is associated to.
So, in my ViewModel, I'd have a list of categorySelectableItems, which has maybe the CategoryId, the DisplayName and a Selected boolean field. To get the data, I need to Select from Categories, LEFT JOIN PayeeCategory, and where PayeeCategoryId is null, set the Selected to false, else true.
How would I do that ina single Linq statement?
Then, when the data comes back... how would I save the data? Would I have to delete all the relationships, and then re-add them based on the List<> values I get back?
Hope someone can guide me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是在另一个问题中回答的。
Linq 查询帮助
This was answered in a different question.
Linq query assistance