【问题标题】:Query a Model regarding its ICollection<> asp.net mvc查询有关其 ICollection<> asp.net mvc 的模型
【发布时间】:2017-04-25 19:27:51
【问题描述】:

使用 EntityFramework6 Code-First mvc 5 我有以下模型:

课程

public class Course
{
    public Course()
    {
        EnrolledStudentsEmails = new HashSet<ApplicationUser>();
    }

    [Key]
    public string Id { get; set; }
    public string UserName{ get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<ApplicationUser> EnrolledStudentsEmails { get; set; }

我正在尝试向 IPagedList(Courses) 查询以下内容

var model =
            (from c in db.Courses
             where searchTerm == null ||
             c.Id.StartsWith(searchTerm) ||
             c.Name.StartsWith(searchTerm)

             select new
             {
                 Id = c.Id,
                 Name = c.Name,
                 Description = c.Description,
                 UserName = c.UserName


             }).AsEnumerable().Select(c => new Course
             {
                 Id = c.Id,
                 Name = c.Name,
                 Description = c.Description,
                 UserName = c.UserName
             }).ToPagedList(page, 10);  

如果我想使用使用用户身份验证时生成的 AspNetUsers 表,ICollection EnrolledStudents 的类型应该是什么?

上面的 LINQ 获取了我数据库中的所有课程。

我如何才能获得 example@123.com 注册的课程? 可以使用我的模型吗?我应该改变我的模型吗?

知道我可以使用以下方式访问电子邮件:

User.Identity.Name

【问题讨论】:

  • 是的,使用用户认证模板创建asp.net应用时生成的

标签: asp.net sql-server asp.net-mvc linq entity-framework-6


【解决方案1】:

如果您现有的代码有效,您的模型是正确的,并且您只想通过已知电子邮件进行过滤,只需使用您的集合:

var emailFilter = "example@123.com";
var model =
            (from c in db.Courses
             where (searchTerm == null ||
               c.Id.StartsWith(searchTerm) ||
               c.Name.StartsWith(searchTerm)) &&
               c.EnrolledStudentsEmails.Any(e => e.Email == emailFilter)

             select new
             {
                 Id = c.Id,
                 Name = c.Name,
                 Description = c.Description,
                 UserName = c.UserName


             }).AsEnumerable().Select(c => new Course
             {
                 Id = c.Id,
                 Name = c.Name,
                 Description = c.Description,
                 UserName = c.UserName
             }).ToPagedList(page, 10);  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多