我有一个objectDao继承的entityDao。我正在使用Dynamic Linq并尝试使一些通用查询起作用。
我在EntityDao的通用方法中有以下代码:
public abstract class EntityDao<ImplementationType> where ImplementationType : Entity
{
public ImplementationType getOneByValueOfProperty(string getProperty, object getValue){
ImplementationType entity = null;
if (getProperty != null && getValue != null)
{
LCFDataContext lcfdatacontext = new LCFDataContext();
//Generic LINQ Query Here
entity = lcfdatacontext.GetTable<ImplementationType>().Where(getProperty + " =@0", getValue).FirstOrDefault();
//.Where(getProperty & "==" & CStr(getValue))
}
//lcfdatacontext.SubmitChanges()
//lcfdatacontext.Dispose()
return entity;
}
然后,在单元测试中执行以下方法调用(我的所有objectDaos都继承了EntityDao):
[Test]
public void getOneByValueOfProperty()
{
Accomplishment result = accomplishmentDao.getOneByValueOfProperty
("AccomplishmentType.Name", "Publication");
Assert.IsNotNull(result);
}
以上通过(AccomplishmentType与成就有关系)
Accomplishment result = accomplishmentDao.getOneByValueOfProperty("Description", "Can you hear me now?");
Accomplishment result = accomplishmentDao.getOneByValueOfProperty("LocalId", 4);
以上两项工作。然而,
Accomplishment result = accomplishmentDao.getOneByValueOfProperty
("Id", New Guid("95457751-97d9-44b5-8f80-59fc2d170a4c"));
不起作用,并显示以下内容:
Operator '=' incompatible with operand types 'Guid' and 'Guid
为什么会这样呢? Guid不能被比较?我也尝试过==
,但是有同样的错误。更令人困惑的是,我看到的每个Dynamic Linq示例都只是使用字符串,而不管使用参数化的where谓词还是我注释掉的那个:
//.Where(getProperty & "==" & CStr(getValue))
使用或不使用Cstr,许多数据类型均不适用于此格式。我也尝试将getValue设置为字符串而不是对象,但是然后我得到了不同的错误(例如多字字符串会在第一个单词之后停止比较)。
使GUID和/或任何数据类型起作用时,我缺少什么?理想情况下,我希望能够只传递一个getValue字符串(就像我在其他每一个动态LINQ示例中所看到的那样)而不是对象,并使它不管列的数据类型如何都可以工作。
抱歉,我发现,动态LINQ最初不支持GUID比较(太愚蠢了!)。我发现了这个小窍门: https ://connect.microsoft.com/VisualStudio/feedback/details/333262/system-linq-dynamic-throws-an-error-when-using-guid-equality-in-where-clause
您只需进入编辑Dynamics.cs,将IEqualitySignatures接口替换为以下内容:
interface IEqualitySignatures : IRelationalSignatures
{
void F(bool x, bool y);
void F(bool? x, bool? y);
void F(Guid x, Guid y);
void F(Guid? x, Guid? y);
}
现在,我的getOneByValueOfProperty一直在工作!
对于Guid,这应该起作用:
.Where(getProperty + ".Equals(@0)", getValue);
(请注意,参数getValue的类型应为Guid )