【问题标题】:How Entity framework works with lambda-expressions in ASP.NET MVC实体框架如何与 ASP.NET MVC 中的 lambda 表达式一起使用
【发布时间】:2013-07-12 17:26:19
【问题描述】:

我首先使用 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 的查询。谢谢。

【问题讨论】:

  • user.Email==User.Identity.Name ?

标签: asp.net-mvc entity-framework lambda


【解决方案1】:

为什么不将DbSet&lt;UserProfile&gt; 添加到您的上下文中,然后这样做:

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();

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

【讨论】:

    【解决方案2】:

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

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

    问题是Where 要求 lambda 表达式返回一个布尔值,而它返回的是一个 IEnumerable&lt;UserProfile&gt;

    【讨论】:

      【解决方案3】:

      因为您想从UserProfile 实体中选择一个特定属性 (Habits),在我看来,最直接的方法是使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-10
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2011-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多