Search code examples
asp.net-mvc-4linq-to-entitiesentity-framework-5partial-classes

Error when projecting partial class properties. The specified type member 'Password' is not supported in LINQ to Entities


I am using MVC4 DatabaseFirst with EF 5. I get this exception: "The specified type member 'Password' is not supported in LINQ to Entities."

enter image description here

My code:

Auto generated class by EF using DB First approach

    // auto-generated-class
    public partial class webpages_Users
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public virtual ICollection<webpages_UsersMenus> webpages_UsersMenus { get; set; }
        public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
    }

Then I created a partial class with a Password property. This will always return blank value and the value will be set from the view.

[MetadataType(typeof(webpages_Users_MD))]
public partial class webpages_Users
{
    public string Password { get {return ""; } }
    class webpages_Users_MD
    {
    }
}

In below line I get exception when I am using Password property:

    var userList = repository.webpages_Users.Select(x => new { x.UserId, x.UserName, x.Password, x.Email }).ToList(); // Error!!!

However, below works fine without password property

    var userList = repository.webpages_Users.Select(x => new { x.UserId, x.UserName, x.Email }).ToList(); // No error here. All ok.

Note: I have to use Select() or something to excude icollection list otherwise jquery used in my view will give error.


Solution

  • I would like to share the answer so anyone struggling with the same issue could refer to this.

    In partial class, the password should be get set so when the form is posted, the controller will get the property value mapped.

    public string Password { get; set; }
    

    And in the controller when returning the list to view replace x.Password with Password = "":

    repository.webpages_Users.Select(x => new { x.UserId, x.UserName, Password = "", x.Email }).ToList();
    

    Blank value will be set for the password property and will be returned to the view.

    Then the jQuery in the view can set the password property and when the form will be posted, webpages_Users.Password value will be accessible