我正在使用存储库模式通过Entity Framework访问数据。 我已经使用洋葱架构正确地实现了所有内容(我认为),但是当我运行测试时,我遇到了以下错误:
Instance Property 'IDDocument' is not defined for type 'System.Int64'
(由法语大致翻译而来)
我测试的方法如下:
public T Get(long id)
{
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
ObjectSet<T> set = objContext.CreateObjectSet<T>();
IEnumerable<string> keyNames = set.EntitySet.ElementType
.KeyMembers
.Select(k => k.Name);
if (keyNames.Count() > 1)
return null;//Que faire quand il y a plusieurs clés?
else
{
string idName = keyNames.ElementAt(0); // For Document would be IDDocument
var parameter = Expression.Parameter(id.GetType());
var property = Expression.Property(parameter, idName);
var idValue = Expression.Constant(id, id.GetType());
var equal = Expression.Equal(property, idValue);
var predicate = Expression.Lambda<Func<T, bool>>(equal, parameter);
return entities.SingleOrDefault(predicate);
}
}
我的表格有不同的ID名称,出于某些原因我不会解释,但这就是为什么我使用Expression builder添加参数并使用谓词检索结果。您可以在此帖子中看到这种方法:Does a Generic Repository need a Base Entity class to be applied everywhere? 在我的EF实体POCO中,IDDocument声明如下:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long IDDocument { get; set; }
当我在测试中调用它时:
[TestMethod]
public void IdExistsGetTest()
{
long valueToCheck = 1L;
repo = new Repository<Web_Documents>(context);
var test = repo.Get(valueToCheck);
test.Should().BeOfType(typeof(Web_Documents));
}
context
定义了我的 dbcontext(在之前被实例化)。
现在当我运行测试时,总是会得到上面提到的 ArgumentException,你有什么想法我漏掉了什么吗?我认为问题出现在 Get(long id) 方法中,因为如果我不使用 Expression
的代码来更改它,它可以正常工作(但不像我想要的那样!)。谢谢
entities.SingleOrDefault(predicate)
的类型时,我得到的不是Web_Documents
,而是类似于Web_Document_8AEAF73BFA0B4906B5153F0BE5CFE91F2DC7F47643CDC9E48189AC7C08E041D2.
的东西。我不明白为什么?可能没有正确理解 SingleOrDefault。 - Flexabust Bergson