Toomaaszo
Toomaaszo

Reputation: 123

Entity Framework, not mapped property in query

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<UserRole> Filter(IQueryable<UserRole> query, string userName, string roleName)
{
    return query.Where(x => x.User.Name.Contains(userName) && x.Role.Name.Contains(roleName));
}

Upvotes: 2

Views: 9476

Answers (1)

Alex Lebedev
Alex Lebedev

Reputation: 609

Basically, if you will do something like

Context.UserRole.Where(x=>x.UserName == "login")

you will have an exception, as you discribed. You can achive this by using

Context.UserRole.Include(x=>x.User).Where(x=>x.User.Name == "login")

Upvotes: 0

Related Questions