Linq查询协助 [英] Linq query assistance

查看:60
本文介绍了Linq查询协助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个屏幕,用户可以在其中选择他们想要订阅的类别.他们可以选择零到许多类别.这些内容存储在UserCategory表中,该表具有一个用户ID和一个类别ID.

I have a screen in which the user can select which categories they want to subscribe to. They can select zero to many categories. These get stored in a UserCategory table, which has a userid and a category id.

因此,如果用户从8个类别中选择2个,我将写两行,其中包含类别ID和用户ID.

So, if the user select 2 out of the 8 categories, I write two rows, with the category ids and the userid.

(他现在被分配了两个类别)

(He is now assigned to TWO categories)

但是,如果用户返回并取消选择一个类别,然后添加2个不同的类别,则他现在被分配给3个类别...

However, if the user returns, and deselects one of the categories, and then adds 2 different categories, he is now assigned to 3 categories...

但是我不确定在linq中处理此问题的好方法...某种程度上,我需要做类似的事情...从UserCategories中删除,其中userId =:UserId和CategoryId不在类别ID的int []中传入....然后我需要将INERT []类别ID插入到UserCategories中,而不是已经存在的类别ID.

But I'm unsure of a good way to handle this in linq... Somehow, I need to do something like ... DELETE FROM UserCategories where userId = :UserId and CategoryId NOT IN the int[] of category ids passed in.... And then I need to INSERT INTO UserCategories ... the int[] category ids, but not the ones that already exist.

我需要使用实体框架在Linq中进行操作...有人可以协助吗?

And I need to do it in Linq, using Entity Framework... Can someone assist?

推荐答案

最简单的解决方案可能是从 all 当前类别中删除该用户,然后将其重新添加到仍处于选中状态的那些类别中.当您可能再次删除并添加相同的信息时,它可以使代码更简单,并且更易于维护.

The simplest solution might be to remove the user from all current categories and re-add to those that are still selected. While you are potentially removing and adding the same information again, it keeps the code simpler and simpler code is easier to maintain.

因此,您将从数据库中读取当前信息,并将其显示在表单上.然后,当用户单击确定"时,清除数据库中的当前信息(当然,将副本保存在内存中),然后将其添加回去,就像这是第一次通过代码进行添加.

So you'd read the current information from the database and present that on the form. Then when the user hits "OK" clear current information in the database (keeping the copy in memory of course) and then add it back as though it was the first time through the code.

这篇关于Linq查询协助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆