Linq2EF:使用 CheckBoxList/ID 值集的结果更新记录

发布于 2024-09-28 08:23:05 字数 320 浏览 0 评论 0原文

假设我在页面上有一个反映表数据的 CheckBoxList。用户取消选中先前选中的项目,并选中未选中的项目。我想使用 LINQ2EF 更新数据库,以便剩余的记录与新提交的检查项目相匹配。

换句话说,当页面提交时,我会得到一个包含已检查 ID 的 String[] 。然后我需要将数据库更新为:

  1. 删除那里的记录,但是 现在没有 ID
  2. 添加不存在的记录,但是 现在已检查 ID
  3. 留下记录,并且 仍然单独检查。

使问题更加复杂的是,提交的 Id 位于字符串数组中,但数据对象的 Id 为 int。

Say I have a CheckBoxList on a page reflecting table data. A user unchecks previously checked items, and checks ones that were not checked. I want to update the database with LINQ2EF so that the records remaining match the newly submitted checked items.

In other words, when the page submits, I get a String[] of checked IDs. I then need to update the database to:

  1. Delete records that were there, but
    now don't have an ID
  2. Add records that were not there, but
    now have IDs checked
  3. Leave records that were there, and
    that are still checked, alone.

Compounding the problem, the submitted Ids are in an array of strings, but the data objects have Id as an int.

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

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

发布评论

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

评论(1

热情消退 2024-10-05 08:23:05

嗯,你写代码。

var submittedAsInts = submittedAsString.Select(s => int.Parse(s));
var toAdd = submittedAsInts.Where(i => !existingEntity.SomeProperty.Any(p => p.Id == i));
var toDelete = existingEntity.SomeProperty.Where(p => !submittedAsInts.Contains(p.Id));
foreach (var delId in toDelete)
{
    var o = existingEntity.SomeProperty.Single(p => p.Id == delID);
    existingEntity.SomeProperty.Remove(o);
    Context.DeleteObject(o);
}
// similarly for insert.

Um, you write code.

var submittedAsInts = submittedAsString.Select(s => int.Parse(s));
var toAdd = submittedAsInts.Where(i => !existingEntity.SomeProperty.Any(p => p.Id == i));
var toDelete = existingEntity.SomeProperty.Where(p => !submittedAsInts.Contains(p.Id));
foreach (var delId in toDelete)
{
    var o = existingEntity.SomeProperty.Single(p => p.Id == delID);
    existingEntity.SomeProperty.Remove(o);
    Context.DeleteObject(o);
}
// similarly for insert.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文