c# - 为什么我不能在 EF4 中的多对多实体上重写 GetHashCode?

标签 c# entity-framework many-to-many gethashcode

我的 Entity Framework 4 模型(与 MS SQL Server Express 一起使用)中存在多对多关系:Patient-PatientDevice-Device。我正在使用 Poco,所以我的 PatientDevice 类如下所示:

public class PatientDevice
{
    protected virtual Int32 Id { get; set; }
    protected virtual Int32 PatientId { get; set; }
    public virtual Int32 PhysicalDeviceId { get; set; }
    public virtual Patient Patient { get; set; }
    public virtual Device Device { get; set; }

    //public override int GetHashCode()
    //{
    //    return Id;
    //}
}

当我这样做时一切正常:

var context = new Entities();
var patient = new Patient();
var device = new Device();

context.PatientDevices.AddObject(new PatientDevice { Patient = patient, Device = device });
context.SaveChanges();

Assert.AreEqual(1, patient.PatientDevices.Count);

foreach (var pd in context.PatientDevices.ToList())
{
    context.PatientDevices.DeleteObject(pd);
}
context.SaveChanges();

Assert.AreEqual(0, patient.PatientDevices.Count);

但是,如果我在 PatientDevice 类中取消注释 GetHashCode,患者仍然拥有之前添加的 PatientDevice。

覆盖 GetHashCode 并返回 Id 有什么问题?

最佳答案

原因很可能是类类型不是哈希码的一部分, Entity Framework 很难区分不同的类型。

尝试以下操作:

public override int GetHashCode()
{
    return Id ^ GetType().GetHashCode();
}

另一个问题是,在某些情况下,GetHashCode() 的结果在对象的生命周期内可能不会改变,这些可能适用于 Entity Framework 。这与 Id 在创建时以 0 开头也会带来问题。

GetHashCode() 的替代方法是:

private int? _hashCode;

public override int GetHashCode()
{
    if (!_hashCode.HasValue)
    {
        if (Id == 0)
            _hashCode.Value = base.GetHashCode();
        else
            _hashCode.Value = Id;
            // Or this when the above does not work.
            // _hashCode.Value = Id ^ GetType().GetHashCode();
    }

    return _hasCode.Value;
}

取自http://nhforge.org/blogs/nhibernate/archive/2008/09/06/identity-field-equality-and-hash-code.aspx .

关于c# - 为什么我不能在 EF4 中的多对多实体上重写 GetHashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4185537/

相关文章:

json - 如何处理 JSON 中的多对多关系?

C# - MVC 4 多对多复选框值传递给另一个 View

jpa - jpql 减去两个计数函数的结果

c# - GetComponent() 或访问字典之间是否存在性能差异?

c# - 如何 - 跨 tcp/ip 边界验证调用程序集

c# - 从极慢的 API 加载或缓存的最快方法?

c# - Entity Framework 代码优先多对多不使用 GUID 加载相关实体

c# - 在 WPF (MVVM) 中使模型静态化是一种好习惯吗?

c# - 如何使用 Linq 从一系列的 3 个表中进行选择?

asp.net-mvc - 如何将两个 LINQ 连接表从 Controller 传递到 View