我有一個簡單的基本實體類型稱爲EntityBase,它實現了IEquatable < EntityBase>。LINQ to Entities是否支持'where'子句謂詞中的IEquatable?
我用這個代碼LINQ 以外的 實體(與EF 4.1)使用where子句,該對象實例,而不是將ID屬性它們從EntityBase繼承比較謂詞以過濾從EntityBase派生類型的列表。所以基本上我想這樣做:
UserAccount account = GetMyNewAccount();
Accounts.Where(item => item == account).SingleOrDefault();
,而不是這樣的:
UserAccount account = GetMyNewAccount();
Accounts.Where(item => item.Id == account.Id).SingleOrDefault();
不幸的是,EF 4.1和專門LINQ 到 實體拋出該異常:
無法創建類型爲「EFTest.UserAccount」的常量值。在此上下文中僅支持基本類型(如Int32,String和Guid)。
這是否意味着我們不能在Entity Framework 4.1中做一個簡單的對象比較謂詞,或者是我的IEquatable實現在某些方面有錯?
P.S:這裏的IEquatable代碼:
public class EntityBase : IEntityBase, IEquatable<EntityBase>
{
public int Id { get; protected set; }
#region IEquatable<EntityBase> Members
public override bool Equals(object obj)
{
return Equals(obj as EntityBase);
}
public bool Equals(EntityBase other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
if (GetType() != other.GetType())
{
return false;
}
return Id.Equals(other.Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
public static bool operator ==(EntityBase a, EntityBase b)
{
if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
{
return true;
}
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a.Equals(b);
}
public static bool operator !=(EntityBase a, EntityBase b)
{
return !(a == b);
}
#endregion
}
其實這是非常合情合理的。在我看來,我之前使用的ORM(Genom-e)(在查詢工作的地方)實際上並沒有實際使用IEquatable方法,而是可以將查詢表達式轉換爲鍵本身的比較 - 它知道關鍵,所以完全有可能。 – Mark 2011-05-27 08:07:21
我可以申請另一位訪問者自己做翻譯,也可以更改所有謂詞。在執行之前修改表達式樹不應該太難。 – Mark 2011-05-27 08:09:56