2

我正在尝试实现具有覆盖等于和 GetHashcode 的抽象基实体类...这是我的实体基类

public abstract class Entity<TId>
{

public virtual TId Id { get; protected set; }
protected virtual int Version { get; set; }

public override bool Equals(object obj)
{
  return Equals(obj as Entity<TId>);
}

private static bool IsTransient(Entity<TId> obj)
{
  return obj != null &&
         Equals(obj.Id, default(TId));
}

private Type GetUnproxiedType()
{
  return GetType();
}

public virtual bool Equals(Entity<TId> other)
{
  if (other == null)
    return false;

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

  if (!IsTransient(this) &&
      !IsTransient(other) &&
      Equals(Id, other.Id))
  {
    var otherType = other.GetUnproxiedType();
    var thisType = GetUnproxiedType();
    return thisType.IsAssignableFrom(otherType) ||
           otherType.IsAssignableFrom(thisType);
  }

  return false;
}

public override int GetHashCode()
{
  if (Equals(Id, default(TId)))
    return base.GetHashCode();
  return Id.GetHashCode();
}

}

实体基 ID 的值是如何分配的?

我的类的主键具有不同的数据类型,并且每个类的名称也不同。这是我的课程示例:

public class Product : Entity
{
    public virtual Guid ProductId { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual Decimal UnitPrice { get; set; }
}

public class Customer : Entity
{
    public virtual int CustomerID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual int Age { get; set; }
}

我对如何设置基类的 ID 属性有点困惑。谁能给我建议,我将不胜感激。

4

1 回答 1

3

您只需要将类型传递给继承的基类。

请参阅实体中的评论:

public class Product : Entity<Guid>
{
    // The ProductId property is no longer needed as the
    // Id property on the base class will be of type Guid
    // and can serve as the Id
    //public virtual Guid ProductId { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual Decimal UnitPrice { get; set; }
}

public class Customer : Entity<int>
{
    // The CustomerID property is no longer needed as the
    // Id property on the base class will be of type int
    // and can serve as the Id
    // public virtual int CustomerID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual int Age { get; set; }
}

现在在您的 NHibernate 映射文件中,只需为您的 Id 属性指定数据库列。

于 2012-08-03T05:51:24.033 回答