I am using a Repository Pattern to access data using Entity Framework. I have implemented everything correctly (I think) using an onion architecture, but when I run tests I get the error :
Instance Property 'IDDocument' is not defined for type 'System.Int64'
(roughly translated from french)
The method I test is the following:
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);
}
}
My tables have different ID names for reasons I won't explain, but this is why I used Expression builder to add parameters and then use a predicate to retrieve my result. You can see this method in this post: Does a Generic Repository need a Base Entity class to be applied everywhere?
IDDocument is declared in the following way in my EF entities' POCO:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long IDDocument { get; set; }
And when I call it in my test:
[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
defines my dbcontext (instantiated before).
Now when I run the tests, I always get the ArgumentException stated above, any idea what I am missing? I think the problem resides in the Get(long id) method, because if I change the code without the Expression
, it works fine (but not like i want it to!). Thanks
I think:
var parameter = Expression.Parameter(id.GetType());
Should be:
var parameter = Expression.Parameter(typeof(T));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With