查询关于其ICollection的模型<> asp.net mvc

时间:2017-04-25 19:27:51

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

使用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(课程)

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

1 个答案:

答案 0 :(得分:0)

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

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