Alecu
Alecu

Reputation: 2708

Solution for IEnumerable.Contains() in entity framework linq queries

I am been using entity framework for my application. Unfortunately I can't make expressions like this one in entity framework:

List<MyUser> users = (from user in database.MyUsers
                      join app in database.MyApplications 
                          on user.ApplicationId equals app.Id
                      where app.Name == this._applicationName 
                          && user.MyRoles.Contains(existingRole)
                      select user).ToList();

Any other approaches to this one. I don't want to change my database or my models. In my case the relationship between MyUser and MyRole is many to many with a glue table.

This is how the MyUser class is declared:

public partial class MyUser
{
    public MyUser()
    {
        this.MyApiTokens = new HashSet<MyApiToken>();
        this.MyLandingPages = new HashSet<MyLandingPage>();
        this.MyPresentations = new HashSet<MyPresentation>();
        this.MySlides = new HashSet<MySlide>();
        this.MyUserSettings = new HashSet<MyUserSetting>();
        this.MyRoles = new HashSet<MyRole>();
    }

    public System.Guid Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string EmailAddress { get; set; }
    public int ApplicationId { get; set; }
    public System.DateTime CreateDate { get; set; }
    public System.DateTime LastActivityDate { get; set; }
    public System.DateTime LastLockoutDate { get; set; }
    public System.DateTime LastLoginDate { get; set; }
    public System.DateTime LastPasswordChangedDate { get; set; }
    public string PasswordQuestion { get; set; }
    public string PasswordAnswer { get; set; }
    public string Comment { get; set; }
    public bool IsLocked { get; set; }
    public bool IsApproved { get; set; }

    public virtual ICollection<MyApiToken> MyApiTokens { get; set; }
    public virtual MyApplication MyApplication { get; set; }
    public virtual ICollection<MyLandingPage> MyLandingPages { get; set; }
    public virtual ICollection<MyPresentation> MyPresentations { get; set; }
    public virtual ICollection<MySlide> MySlides { get; set; }
    public virtual ICollection<MyUserSetting> MyUserSettings { get; set; }
    public virtual ICollection<MyRole> MyRoles { get; set; }
}

Upvotes: 2

Views: 1702

Answers (1)

sinelaw
sinelaw

Reputation: 16553

Assuming MyRoles is an association property in the entity model (i.e. maps to a table), you may want to make the matching explicit on the primary key of the role object. For example:

user.MyRoles.Any(r => r.RoleId == existingRole.RoleId)

There isn't enough information in your question to give an exact answer, though.

Upvotes: 3

Related Questions