简体   繁体   中英

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. 示例模型

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));
}

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM