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

前端 未结 1 1426
遇见更好的自我
遇见更好的自我 2021-01-16 00:35

I am creating an Intranet website with ASP.NET MVC and Onion Architecture. I have been implementing the repository pattern but I have a difficulty.

1条回答
  •  太阳男子
    2021-01-16 01:15

    You're calling the Queryable.SingleOrDefault method.

    Its second parameter has the type Expression> 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>(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.

    0 讨论(0)
提交回复
热议问题