我正在粘贴下面的代码;
我的基类重写了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 :(得分:2)
查询在服务器端执行(在数据库中)。 重写equals或gethashcode没有任何区别。
只需选择id属性,然后在最后调用Distinct。 您将不得不迭代结果以获取更多信息。
OR
您可以使用联接来获取从子查询返回的ID的详细信息。