I’d like to change the default behavior of .Where method for specific case(s).
All my Business Objects inherit from BaseObject that has property int ID {get; set;}
// Base class
public abstract class BaseObject
{
public abstract int ID {get; set;}
}
I have 2 classes:
public partial class User : BaseObject
{
public override int ID {get; set;}
public string Username { get; set; }
public int ProfileID { get; set; }
public virtual Profile Profile { get; set; }
}
public partial class Profile : BaseObject
{
public override int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
public static Profile GetAdminProfile()
{
return new Profile(){ID = 3, Name = "Admin profile"};
}
}
I would like to write
// This throws Unable to create a constant value of type 'Profile'... exception
User admin = Users.Where(user.Profile == Profile.GetAdminProfile()).FirstOrDefault();
instead of
User admin = Users.Where(user.Profile.ID == Profile.GetAdminProfile().ID).FirstOrDefault();
Is there a way to achieve this?
This is a known problem in Entity Framework. You will have follow the second approach.