2012-08-02 56 views
1

我想實現已經重寫平等和GetHashCode抽象基實體類...這裏是我的實體基類NHibernate和實體基類

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(); 
} 

}

如何實體的值基地標識被分配?

我的類的主鍵具有不同的數據類型,每個類的名稱也不同。 這裏是我的課的樣本:

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屬性有點糊塗了。任何人都可以請建議我,我會很感激任何幫助。

回答

2

你只需要傳遞一個類型到繼承的基類。

看評論中的實體:

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屬性。