Entity Framework, not mapped property in query
04:18 15 Sep 2015

I'm creating an entity model in which I want to put a not mapped properties. These properties are there to simplify access to values from relationship. Model shown is just a simple example. Example model

In users_roles entity, named UserRole, I want to have UserName property and RoleName.

public class UserRole 
{
    public int Id { get; set; }
    public int IdUser { get; set; }
    public int IdRole { get; set; }

    public User User { get; set; }
    public Role Role { get; set; }

    [NotMapped]
    public string UserName
    {
        get { return User.Name; }
    }
    [NotMapped]
    public string RoleName
    {
        get { return Role.Name; }
    }
}

It's important for me for future filtering, databinding, etc. I do not insist on such a solution. It's just a first idea.

For now, if I try to filter entities by UserName or RoleName I have an exception, because NotMapped properties don't exist in the database.

Second thing is getting a value of properties after DbContext dispose. For now I'm using .Include() method (Eager Loading), but is it possible to get both above functionality (filterint, etc. and eager loading values) in one way?

Edit 1: I'm using Code First strategy of model creation. Edit 2: Ok, to clarify, the most basic answer is to create a filter method like that

public IQueryable Filter(IQueryable query, string userName, string roleName)
{
    return query.Where(x => x.User.Name.Contains(userName) && x.Role.Name.Contains(roleName));
}
c# entity-framework dbcontext