0

我首先使用 EF 代码。有两个类定义了我的多对多关联表:

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Habit> Habits { get; set; }
}



public class Habit
{
    [Key]
    public int HabitId { get; set; }

    public virtual ICollection<UserProfile> Users { get; set; }
}

我需要从我的数据库中选择当前用户的所有习惯。我对 c# 很陌生,问题是我无法理解如何使用复杂的 lambda 表达式。我试过了:

context.Habits.Where(habit => habit.Users
                .Where(user=>user.Email==User.Identity.Name)).ToList()

但这是错误的。您能否更正我的基于 lambda 的查询。谢谢。

4

3 回答 3

2

为什么不将 a 添加DbSet<UserProfile>到您的上下文中,然后执行以下操作:

context.Users.Include("Habits")
       .First(user => user.Email == User.Identity.Name)
       .Habits;

如果您想避免上述情况,而是要修复您应该执行的查询:

context.Habits.Where(habit =>                   
           habit.Users.Any(user=>user.Email==User.Identity.Name)).ToList();

Any如果 IEnumerable 中的任何项满足条件,则返回 true。

于 2013-07-12T17:45:56.827 回答
0

尝试对第一个 lambda 表达式使用 Select(或 SelectMany,如果您想要一个扁平列表):

context.Habits.Select(habit =>
    habit.Users.Where(user => user.Email == User.Identity.Name)
    ).ToList()

问题是Where要求 lambda 表达式返回一个布尔值,并且它返回一个IEnumerable<UserProfile>.

于 2013-07-12T17:37:09.583 回答
0

因为您想从实体中选择特定属性 ( Habits),所以我认为UserProfile最直接的方法是使用Select

var habits = context.UserProfiles
    .Where(user => user.Email == User.Identity.Name)
    .Select(user => user.Habits)
    .SingleOrDefault(); // I assume here that the Email is unique
于 2013-07-12T20:08:00.417 回答