实体框架6在执行where子句时强制转换继承对象

时间:2015-02-05 13:02:50

标签: entity-framework

让我说我有一个评论表, 管理员和会员可以对其进行评论。 Admin和Member是User的继承, 所以现在我想得到评论并按成员(groupName)的特定属性过滤

public class User
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; } //member or admin
}
public class Admin : User
{
    public string someProp { get; set; }
}
public class Member : User 
{
    public string groupName { get; set; }
}
public class Comment
{
    [Key]
    public int id { get; set; }
    public string msg { get; set; }
    [ForeignKey("user")]
    public int user_id { get; set; }

    public virtual User user { get; set; }
}

var comments = db.comments.Where(c => c.user.type == "member" && c.user.groupName == "abc").ToList(); 

当然上面的代码无法正常工作, 所以对我有任何想法?

1 个答案:

答案 0 :(得分:2)

试试这个:

var comments = db.comments.Where(c =>
    c.user is Member &&
    (c.user as Member).groupName == "abc"
);

此外,如果您要公开关联的另一端(用户 - >评论),它可能会更容易:

public abstract class User
{
    [Key]
    public int id { get; set; }
    public string name { get; set; }
    public string type { get; set; } //member or admin

    public virtual ICollection<Comment> Comments { get; set; }
}

然后:

var comments = db.users
                 .OfType<Member>()
                 .Where(x => x.groupName == "abc")
                 .SelectMany(x => x.Comments);

P.S我冒昧地将您的User课程标记为abstract