Does a Generic Repository need a Base Entity class to be applied everywhere?

為{幸葍}努か 提交于 2019-12-01 13:03:31

You're calling the Queryable.SingleOrDefault method.

Its second parameter has the type Expression<Func<T, bool>> so you can build expression manually, using as identifier property as you wish.

Short example:

public T Get(long id)
{
    var idName = "ID" + typeof(T).Name; // 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);
}

Imagine you wrote lambda function (T obj) => obj.IdProperty == id. Here obj is parameter, and idName should store "IdProperty" string. property means obj.IdProperty, idValue means the value if id. equal means obj.IdProperty == id, and predicate means whole expression (T obj) => obj.IdProperty == id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!