【发布时间】: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.cs 和INHibernateProxy.cs,但我无法理解这种方法的作用。
【问题讨论】:
标签: ef-core-6.0