0

I have a table in database that has some columns.I get a list of some records from this table in my repository class.So I will have something like this:

enter image description here

Now I want to delete records that have the same value in a special column(here in Code column),like this:

enter image description here

I mean I want to have just one of the records that have the same Code column value. How can I do that in Entity Framework?

4

2 回答 2

0

让您有两个表Table1table2并且您想删除table2 table1中具有相同编号的所有记录。这是你的要求code

1.首先你必须得到表2的代码列的所有值

  1. var x = db.table2.Select(p => p.code); 然后,您必须在删除这些代码的记录后将其与 table1 进行比较。
  2. 为此,您必须在下面编写一段代码。

    foreach (var item in x) { var y = db.table1.Where(p => p.code== item).FirstOrDefault(); if (y != null) { db.table1.DeleteObject(y); db.SaveChanges(); } 别的 { } }

于 2013-03-05T09:22:40.103 回答
0

Code列分组,跳过每组的第一条记录并删除其余记录:

var query = db.Records.GroupBy(r => r.Code)
              .Select(grouping => grouping.OrderBy(ent => ent.EntityId).Skip(1));

foreach (var element in query.SelectMany (q => q))
{
    db.Records.Remove(element);
}

db.SaveChanges();
于 2013-03-05T09:46:46.483 回答