The specified type member is not supported in LINQ

2019-09-09 02:55发布

问题:

public partial class User : IUser
{
    public long ID {get; set;}

    public BaseUser BaseUser
    {
        get
        {
            var context = new Factory().Create<ContextDB>();

            return context.Users.Find(this.ID);
        }
    }
}

and

var result = _Context.Employees.Where(t => t.User.BaseUser.UserName.ToLower().Trim().Contains(searchKey));

Here I am getting an exception:

The specified type member 'BaseUser' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Any solution to this?

回答1:

You have written Linq query. And you are working with Entity Framework. So, you are using Linq-To-EntityFramework.

.Net will translate your Linq query to database query based on the type of the RDMS which you are using. For example, let's take this code:

context.Users.Select(x => x.Id == 5);

This will be translated to:

select * from User where Id=5;

So, it means that .net will throw exception if it couldn't translate it to the database query. For example, your query. You have created property in your class. And you are beleiving that it will be translated to the database query? How? There is no way! This is the reason of the exception.

Also, your BaseUser property seems unusual to me. BaseUser will be same with User if you have configured everything right.