【问题标题】:What would be equivalent to NHibernateProxyHelper.GetClassWithoutInitializingProxy in EF Core 6?什么相当于 EF Core 6 中的 NHibernateProxyHelper.GetClassWithoutInitializingProxy?
【发布时间】:2022-01-25 18:01:30
【问题描述】:

我正在尝试理解领域驱动设计。我正在关注的示例程序使用 NHibernate。它有一个Entity 基类,如下所示:

public abstract class Entity
{
    public virtual long Id { get; protected set; }

    public override bool Equals(object obj)
    {
        var other = obj as Entity;

        if (ReferenceEquals(other, null))
            return false;

        if (ReferenceEquals(this, other))
            return true;

        if (GetRealType() != other.GetRealType())
            return false;

        if (Id == 0 || other.Id == 0)
            return false;

        return Id == other.Id;
    }

    public static bool operator ==(Entity a, Entity b)
    {
        if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
            return true;

        if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
            return false;

        return a.Equals(b);
    }

    public static bool operator !=(Entity a, Entity b)
    {
        return !(a == b);
    }

    // Finally, we also need to implement the GetHashCode method.
    // It's important for two objects which are equal to each other to always
    // generate the same hash code.
    // Here the hash code depends on the object's type and identifier,
    // which are the parts of the object's identity
    // https://stackoverflow.com/q/371328/1977871
    public override int GetHashCode()
    {
        return (GetRealType().ToString() + Id).GetHashCode();
    }

    private Type GetRealType()
    {
        // Here is the question. What would the equavalent of the following in EF Core? 
        return NHibernateProxyHelper.GetClassWithoutInitializingProxy(this);
    }
} 

我对 NHibernate 很陌生。那是什么

NHibernateProxyHelper.GetClassWithoutInitializingProxy(this);

如何将其转换为 EF Core 6?

NHibernate 在实体之上创建代理类并覆盖其中的所有非私有成员,NHibernate 使用反射创建这些实体。

GetType 方法将返回代理的类型,而不是底层实体的类型。因此,为了解决这个问题,我们引入了一个GetRealType 方法,该方法将检索实体的真实类型,而不管其上是否有代理。它利用了 NHibernate 库中的一种实用方法。

所以问题来了。这将如何使用 EF Core 6 进行翻译?我只是猜测 EF Core 也会生成类似于 NHibernate 的代理。那么什么相当于

NHibernateProxyHelper.GetClassWithoutInitializingProxy(this);

我正在看NHibernateProxyHelper.csINHibernateProxy.cs,但我无法理解这种方法的作用。

【问题讨论】:

    标签: ef-core-6.0


    【解决方案1】:

    EF 核心等效项是

    Type GetRealType(object obj)
    {
        var typ = obj.GetType();
        return obj is Microsoft.EntityFrameworkCore.Proxies.Internal.IProxyLazyLoader
            ? typ.BaseType
            : typ;
    }
    

    IProxyLazyLoader 标头中的免责声明:

    您应该非常谨慎地直接在代码中使用它,并且知道这样做会在更新到新的 Entity Framework Core 版本时导致应用程序失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多