访问LINQ查询的ASP.NET模型而不是数据库中的值

时间:2018-10-07 18:34:26

标签: linq

我正在Angular 5中构建此Web应用程序的前端,并在ASP.NET 4.6.1,Entity Framework 6.2.0中构建后端。我在Angular中构建了一个POST http调用,以将int(从选项下拉列表中)发布到后端的模型中。这个名为ViewModelLocation的模型应该存储此值(位置编号),以便我可以在linq查询中访问位置编号。

因此,我不希望该值发布到数据库(数据库中没有此表),因为我只想使用此数字进行过滤,并让所有学生都到达位置编号(在Angular中选择)。邮寄电话似乎有效,但我不知道如何编写此linq查询(因为该号码不在我的数据库中)并返回学生。我可能会以错误的方式处理(?),我也想看看这个值发布到后端后的含义。

这是我尝试在linq中的StudentsController中...

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using ContentMastAPI.Models;

namespace ContentMastAPI.Controllers
{
    public class StudentsController : ApiController
    {
        private Model1 db = new Model1();

        // GET: api/Students
        public IQueryable<Student> GetStudents()
        {
            // TRYING TO RETURN ALL STUDENTS FROM SELECTED LOCATION
            var returnStudents = db.Students.Where(s => s.location == ViewModelLocation.OptionSelectId);

            return returnStudents;

            return db.Students;
        }
    }
} 

这是我的模特班:

using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ContentMastAPI.Models
{
    public class ViewModelLocation
    {
        [Key]
        public int OptionSelectId { get; set; }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该真正将视图模型和数据库模型分开。 现在,您的get方法没有参数(例如,它什么也没接收)。您需要添加参数才能在过滤中使用它。

// No need for returning IQueryable since receiver will have no use of it.
public IEnumerable<StudentViewModel> GetStudents(int locationId)
{
    var entities = db.Students.Where(s => s.LocationId == locationId);
    return entities.Select(e => new StudentViewModel
    {
         // Map your entity properties to view model properties
    };
}

还要考虑将位置属性更改为Pascal大小写(reference)。