2017-05-26 40 views
0

我想申請/練習DDD與我的新項目,因此我創建了那些典型的DDD基類,即Entity,ValueObject,AggregateRoot等等。DDD實體 - 兩個實體的默認身份認爲是相等的

問: 當你有實體基本對象實施IEquatable,應與標識(ID)的默認值,兩個實體被視爲不等於等於

例如,我用Guid類型的身份

public interface IEntity 
{ 
    Guid LocalId { get; } 
} 

public abstract class Entity : IEntity, IEquatable<Entity> 
{ 
    public Guid LocalId { get; private set; } 

    protected Entity() 
    { 
     this.LocalId = Guid.Empty; 
    } 

    protected Entity(Guid id) 
    { 
     if (Guid.Empty == id) 
     { 
      id = Guid.NewGuid(); 
     } 

     this.LocalId = id; 
    } 

    public bool Equals(Entity other) 
    { 
     if (ReferenceEquals(other, null)) 
     { 
      return false; 
     } 
     if (ReferenceEquals(other, this)) 
     { 
      return true; 
     } 

     // **Question** - should I return false or true here? 
     if (other.LocalId == Guid.Empty && this.LocalId == Guid.Empty) 
     { 
      return false; 
     } 

     return (other.LocalId == this.LocalId); 
    } 

    public override bool Equals(object obj) 
    { 
     if (ReferenceEquals(obj, null)) 
     { 
      return false; 
     } 
     if (ReferenceEquals(obj, this)) 
     { 
      return true; 
     } 
     if (!obj.GetType().Equals(typeof(Entity))) 
     { 
      return false; 
     } 

     return Equals((Entity)obj); 
    } 

    public override int GetHashCode() 
    { 
     return this.LocalId.GetHashCode(); 
    } 

    public static bool operator==(Entity left, Entity right) 
    { 
     return Equals(left, right); 
    } 

    public static bool operator!=(Entity left, Entity right) 
    { 
     return !Equals(left, right); 
    } 
} 
+0

只是一個問題不相關的問題:它是一個C#的事來定義這個基地clases?在'PHP'中,我喜歡避免繼承,特別是在域對象(實體,聚合根,值對象)中。 –

+0

@Constantin:不,它不是C#的東西:) ---這是一些人設計的選擇。我不使用這些,也不會推薦它。沒有傷害,但也沒有真正增加多少價值恕我直言。 –

+0

@David,回答你的問題:從技術上講,「對象」是相同的,但從業務角度來看,擁有沒有密鑰的實體/集合體是沒有意義的,平等或缺乏平等沒有意義。 –

回答

0

如果你想跟着書上的這則記得:

不是由它的屬性定義的一個對象,而是由一個連續性和其身份的線程組成。

現在,在這種情況下身份意味着,在大多數情況下是指實體的主鍵(如果你的實體保存在一個數據庫)或某種「從其他對象區分開來的對象的財產」的Id屬性,在大多數情況下,一個GUID將做到這一點。

因此,要回答你的問題:

  1. 是的,他們是同一實體。
  2. 小心你如何創建 標識的
+0

然後,我應該刪除空的構造函數實體(),以便我可以強制子類傳遞一個Id到它? –

+0

我會的,但這只是一個風格問題。 – yorodm