0

我正在使用实体框架 6 来开发我的 c# 应用程序。我已将我的数据模型命名为分配模型,并且我有一个名为 JobTable 的表。

我的数据库模型类看起来像这样

 public partial class  Allocation : DbContext
    {
        public  Allocation()
            : base("name=Allocation")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
        public virtual DbSet<JOB_Header> JOB_Header { get; set; }
    }

我的工作标题看起来像这样

我的 Job 标题类看起来像这个 Job jeader 类是从我的表 Job_header 的实体框架工作模型生成的类

public partial class JOB_Header
    {
        public int JobID { get; set; }
        public string CustomerCode { get; set; }
        public string CustomerName { get; set; }
        public string MobileNo { get; set; }
        public string LocationCode { get; set; }
        public System.DateTime JobDate { get; set; }
        public bool Status { get; set; }
        public string Remarks { get; set; }
    }

如何查询以下 sql 查询的数据?

SELECT TOP 1 * FROM JOB_Header ORDER BY JOBID DESC;

select CustomerName from JOB_Header where JobID =1;



using (DataControllers.AllocationJAEntities = new DataControllers.Allocation())
            {
                JHeaderModel = JAEntities.JOB_Header.Where(a => a.JobID == 1).FirstOrDefault();
            }

通常我会得到像上面这样的对象的数据。但我需要获取单个字段而不读取数据到为数据模型中为表创建的类的对象获取对象的所有行详细信息。如何以这种方式处理正常查询?

4

3 回答 3

4
using (var context = new DataControllers.Allocation())
{
  var header = context.JOB_Header.OrderByDescending(j => j.JobID).FirstOrDefault();
}

不确定你的变量名,所以我自己写

于 2018-12-05T06:07:25.603 回答
2

为什么你不能像下面那样选择那个字段。此外,如果您JobID是一个关键字段(看起来像),那么我根本不需要,FirstOrDefault()因为它Where()只会返回一条记录

JAEntities.JOB_Header.Where(a => a.JobID == 1).Select(x => x.CustomerName)
于 2018-12-05T06:03:50.780 回答
2

当我们只想获得您可以通过以下更改执行的名称时。这个概念是当你找到我的KEY时候,就会有NOOne记录在最大值。然后 -

string name = string.Empty;
using (DataControllers.AllocationJAEntities = new DataControllers.Allocation())
{
    name = JAEntities.JOB_Header.Find(1)?.CustomerName;
}

注意我使用了该Find方法,因为我们使用主键搜索,否则我们也可以使用WHERE

请记住,如果您Find实际使用它,它将查询您的数据库以获取完整的行,如下面的 SQL 查询 -

从 Id = 1 的表中选择 *

意味着您的 DB 整行将针对您的特定 ID 返回到您的代码,然后您正在阅读您的 name 属性。

但是,当您想要实现以下 SQL 查询时 -

SELECT CustomerName FROM table WHERE Key = 1

对于这种情况,Rahul 的回答是正确的。-

string name = string.Empty;
using (DataControllers.AllocationJAEntities = new DataControllers.Allocation())
{
    name = JAEntities.JOB_Header
            .Where(a => a.JobID == 1)
            .Select(x => x.CustomerName)
            .FirstOrDefault();
}

要获得包括订单在内的第一条记录,您可以(如上所述斯蒂芬)-

using (var context = new DataControllers.Allocation())
{
  var job = context.JOB_Header.OrderByDescending(j => j.JobID).FirstOrDefault();
}
于 2018-12-05T06:22:48.643 回答