【发布时间】:2017-06-21 15:05:52
【问题描述】:
我正在使用存储库模式通过实体框架访问数据。我已经使用洋葱架构正确实现了一切(我认为),但是当我运行测试时出现错误:
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 名称,但这就是我使用表达式生成器添加参数然后使用谓词检索结果的原因。你可以在这篇文章中看到这个方法:Does a Generic Repository need a Base Entity class to be applied everywhere?
IDDocument 在我的 EF 实体的 POCO 中以下列方式声明:
[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 的情况下更改代码,它可以正常工作(但不像我想要的那样!)。谢谢
【问题讨论】:
标签: c# sql-server entity-framework repository-pattern