Cast Entity to Implemented Interface in a Generic Method Using LINQ for Entity Framework

前端 未结 3 1761
滥情空心
滥情空心 2020-12-10 04:19

I have a generic method to query objects of type TEntity in EF. I Want to add a condition as a where clause if TEntity implements a specific interface. The method I have is:

3条回答
  •  我在风中等你
    2020-12-10 05:08

    If all DbSets has the 'UserID' property then create another interface named 'IUserID' and then try this code:

        protected TEntity GetByUserID(Guid userID) where TEntity : class
        {
            var user = this.Set()
                .ToList()
                .Cast()
                .Where(u => (!u.IsDeleted))
                .Cast()
                .Where(u => (u.UserID == userID))
                .FirstOrDefault();
            return user;
        }
    

提交回复
热议问题