什么是比较两个实体框架实体的最佳方式? [英] What is the best way to compare two entity framework entities?

查看:141
本文介绍了什么是比较两个实体框架实体的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道比较同一类型的两个实体的最有效的方法。

I want to know the most efficient way of comparing two entities of the same type.

一个实体是从一个xml文件手工创建的手动设置属性),另一个从我的对象上下文中恢复。

One entity is created from an xml file by hand ( ie new instance and manually set properties) and the other is retvied from my object context.

我想知道每个实例中的属性值是否相同。

I want to know if the property values are the same in each instance.

我的第一个想法是从每个对象生成属性值的哈希,并比较哈希,但可能有另一种方式,或者内置的方式?

My first thoughts are to generate a hash of the property values from each object and compare the hashes, but there might be another way, or a built in way?

欢迎任何建议。

非常感谢,

James

UPDATE

我想出了这一点:

static class ObjectComparator<T>
{
    static bool CompareProperties(T newObject, T oldObject)
    {
        if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
        {
            return false;
        }
        else
        {
            var oldProperties = oldObject.GetType().GetProperties();

            foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

                    if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
    }
}

一个可能是一个问题的事情是比较具有实体值本身的属性,如果默认比较器比较对象引用,那么它永远不会是真的。可能的解决方法是重载我的实体上的等式运算符,以便在实体ID上进行比较。

One thing that might be a problem is comparing properties that have entity values themselves, if the default comparator compares on object reference then it will never be true. A possible fix is to overload the equality operator on my entities so that it compares on entity ID.

推荐答案

你的对象,并编写一个实现,比较使它相等的属性。

Override the Equals method of your object and write an implementation that compares the properties that make it equal.

    public override bool Equals(object obj)
    {
        return MyProperty == ((MyObject)obj).MyProperty
    }

这篇关于什么是比较两个实体框架实体的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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