使用多个列的实体框架查找SQL表中的所有重复记录

时间:2015-05-08 06:41:11

标签: c# entity-framework

我尝试将此查询重构为EF查询:

SELECT 
    PS_Adressen.AdName, PS_Adressen.AdVorname, 
    PS_Adressen.AdStrasse, PS_Adressen.AdStrasseNr, PS_Adressen.AdPLZ6  
FROM
    PS_Besuch 
JOIN 
    PS_Adressen ON PS_Besuch.BeAdNr = PS_Adressen.Adnr 
WHERE
    BeAbMonat = @Month 
    AND BeHostessNr = @Nr 
    AND (PS_Besuch.BeKoffer = 1 OR PS_Besuch.BeKoffer = 2 
         OR PS_Besuch.BeKoffer = 3) 
GROUP BY
    PS_Adressen.AdName, PS_Adressen.AdVorname, 
    PS_Adressen.AdStrasse, PS_Adressen.AdStrasseNr, PS_Adressen.AdPLZ6 
HAVING
    COUNT(BeNr) > 1

我发现了这篇文章:Find all duplicate records in SQL table with Entity Framework

但这只能让我检查一个像名称这样的值是否重复,而不是不同的列。

我开始时:

var query = from visit in db.Visits
            join address in db.Addresses on visit.AddressId equals address.Id
            group address by new {
                        address.Name,
                        address.Prename,
                        address.Street,
                        address.StreetNr,
                        address.Zip,
                        address.ZipLong,
                        visit.VisitNr
                    } into temp
            select  new {
                    Name = temp.Key.Name,
                    Prename = temp.Key.Prename,
                    Street = temp.Key.Street,
                    StreetNr = temp.Key.StreetNr,
                    Zip = temp.Key.Zip,
                    ZipLong = temp.Key.ZipLong,
                    VisitNr = temp.Key.VisitNr
                };

var list = query.Where(x => x.VisitNr.Count() > 1).ToList();

但是这里的where子句不正确。伯爵的一些东西似乎错了..

谁能告诉我我做错了什么?

由于 NPadrutt

1 个答案:

答案 0 :(得分:1)

试试这段代码:

var query = from visit in db.Visits

                    join address in db.Addresses on visit.AddressId equals address.Id

                    group address by new {
                        address.Name,
                        address.Prename,
                        address.Street,
                        address.StreetNr,
                        address.Zip,
                        address.ZipLong
                    } into temp
                select  new {
                    Name = temp.Key.Name,
                    Prename = temp.Key.Prename,
                    Street = temp.Key.Street,
                    StreetNr = temp.Key.StreetNr,
                    Zip = temp.Key.Zip,
                    ZipLong = temp.Key.ZipLong,
                    RecCount = temp.Count()
                };

            var list = query.Where(x => x.RecCount > 1).ToList();