2010-01-20 52 views
2

我粘貼下面的代碼;linq截然不同的結果

我的基類重寫Equals和getHashcode,但linq查詢沒有返回不同的結果。結果中有多個城市具有相同的ID。

public class Product : EntityBase 
    { 
     public virtual string Name { get; set; } 

     public virtual IList<ProductDayDefinition> Days { get; set; } 
    } 

    public class ProductDayDefinition : EntityBase 
    { 
     public virtual Product Product { get; set; } 

     public virtual City City { get; set; } 

    } 


public abstract class EntityBase 
    { 
     public virtual int ID { get; protected internal set; } 

     protected EntityBase() : this(0) 
     { 

     } 

     protected EntityBase(int ID) 
     { 
      this.ID = ID; 

      if (this.ID == null) 
       this.ID = 0; 
     }   

     #region Equals definitions 
     public override bool Equals(object entity) 
     { 
      return entity != null 
       && entity is EntityBase 
       && this == (EntityBase)entity; 
     } 

     public static bool operator ==(EntityBase base1, EntityBase base2) 
     { 
      if ((object)base1 == null && (object)base2 == null) 
       return true; 

      if ((object)base1 == null || (object)base2 == null) 
       return false; 

      if (base1.ID != base2.ID) 
       return false; 

      return true; 
     } 

     public static bool operator !=(EntityBase base1, EntityBase base2) 
     { 
      return (!(base1 == base2)); 
     } 

     public override int GetHashCode() 
     { 
      return this.ID.GetHashCode(); 
     } 
     #endregion 
    } 

var cities = (from product in NHibernateSession.Linq<Product>() 
       from day in product.Days 
       where day.City != null 
       select day).Distinct(); 
+0

你'選擇日',但變量名爲'城市'。你的預期產出是多少? – 2010-01-20 14:33:44

回答

2

查詢在服務器端(在數據庫中)執行。 覆蓋equals或gethashcode沒有任何區別。

只需選擇id屬性,然後在最後調用Distinct。 您必須遍歷結果才能獲取更多信息。

OR

您可以使用一個連接來獲取ID的細節從子查詢返回。

http://msdn.microsoft.com/en-us/library/cc716801.aspx

+0

會有解決我的問題? – GuestMVCAsync 2010-01-20 10:35:51