开发者

Entity Framework 4.0: .Equals compare to find dups but ignore keys

I'm using Entity Framework 4.0. I want to be able to find duplicate records in an EntitySet. The records will have the same data but different primary keys. When I do a .Equals I get that the records are not equal. I know I can override .Equals but I've got over 20 related entities each with a lot of fields.

Is there a compare method available that will look at all the fields except the key to tell me if they're the same?开发者_如何转开发

Seems like this would be a common issue and I can't imagine it hasn't been solved already.

Thanks for any advice...


Instead of overriding the .Equals() method, you can use its overload to specify your own IEqualityComparer...

Also, if you just want the de-duped or distinct values, you can use the .Distinct() method, or you can do a LINQ group-by query to isolate criteria that has more than one match...

var sample = from a in sampleA join b in sampleB 
on a.SampleProperty equals b.SampleProperty 
into c select c.FirstOrDefault();

http://msdn.microsoft.com/en-us/library/ms132151.aspx


I've resolved to generate the code to create .Equals() overrides using a T4 template. It goes something like this:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.IO" #>
<#@ assembly name="System.Data.Entity" #>
<#@ assembly name="C:\<MyProjectLibPath>\bin\Debug\MyLib.dll" #>
<#@ import namespace="MyNamespace.Models" #>
<#
    var className = "<MyClass>"; // <-- change this to class name
    var stringProps = typeof(<MyClass>).GetProperties();
#>

namespace MyNamespace.Models
{
    partial class <#= className #>
    {
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (GetType() != obj.GetType()) return false;

            var section = obj as <#= className #>;
            if (section == null) return false;

            return 

            <# for(var i=0; i<stringProps.Length; i++)
            { 
                var element = stringProps[i];
                if(element.Name != "ClaimRecId" && element.Name != "EntityState" && element.Name != "EntityKey" 
                    && element.Name != "EntityState" && element.Name != "MAEW_FILE_REC_SECTION" && !element.Name.EndsWith("Reference")) { #>
                section.<#= element.Name #> == <#= element.Name #> <#= string.Format("{0}",(i<(stringProps.Length-5))?"&&":"") #>
              <# }
            } #>;
        }
    } // class
} // namespace

I also discovered that Resharper will generate a .Equals() override.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜