如何在EntityFramework 4.1中更改.Where方法的默认行为?

时间:2011-10-07 18:43:58

标签: linq entity-framework-4.1

我想针对特定情况更改.Where方法的默认行为。

我的所有Business Objects都从BaseObject继承了属性int ID {get; set;}

// Base class
public abstract class BaseObject
{
    public abstract int ID {get; set;}
}

我有2个班级:

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

我想写

// This throws Unable to create a constant value of type 'Profile'... exception
User admin = Users.Where(user.Profile == Profile.GetAdminProfile()).FirstOrDefault();

而不是

User admin = Users.Where(user.Profile.ID == Profile.GetAdminProfile().ID).FirstOrDefault();

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

这是实体框架中的已知问题。你将遵循第二种方法。