简体   繁体   English

从实体框架SqlQuery访问未映射的实体

[英]Accessing un-mapped entities from Entity Framework SqlQuery

I am using Entity Framework, I have an entities class which has 2 fields: 我正在使用实体框架,我有一个实体类,其中包含2个字段:

  • Name 名称
  • Description 描述

I have a stored procedure which is returning exact above entities plus an additional entity called TotalRecords . 我有一个存储过程,该过程返回上面的实体以及另外一个称为TotalRecords实体。 I created a new entity in my above class called TotalRecords and added an attribute [NotMapped] to it. 我在上面的类中创建了一个名为TotalRecords的新实体,并向其添加了[NotMapped]属性。

Now when I call the stored procedure, it does not map to the new entity TotalRecords ; 现在,当我调用存储过程时,它不会映射到新实体TotalRecords I understand because I have added an attribute [NotMapped] on it, but if I don't apply that attribute, it will simply create a new column in my database table, which isn't my intention. 我理解是因为我在上面添加了一个属性[NotMapped] ,但是如果我不应用该属性,它只会在数据库表中创建一个新列,这不是我的意图。

Here's how I am calling SqlQuery to execute stored procedure: 这是我调用SqlQuery来执行存储过程的方法:

var _products = db.Products.SqlQuery("GetProductsByCategory @p0,@p1,@p2", categoryID, pageIndex, Common.PAGE_SIZE).ToList();

Could anyone tell me how could I get the TotalRecords field from stored procedure, without adding new column in the database? 谁能告诉我如何从存储过程中获取TotalRecords字段,而无需在数据库中添加新列? As I said above, I have just one column extra rest all are being mapped to the database table Products 正如我前面所说,我只有一个列额外,其余全部被映射到数据库表的Products

All you have to do is create an object that has the same property names as the results returned by the stored procedure. 您要做的就是创建一个对象,该对象的属性名称与存储过程返回的结果相同。 You can try following the sample. 您可以尝试遵循示例。 Hope to help, my friend. 希望对您有帮助,我的朋友。

1) The first, create a class like this: 1)首先,创建一个像这样的类:

public class ProductResult
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public decimal TotalRecords { get; set; }
    }

2) And then call the procedure: 2)然后调用程序:

using(var context = new DatabaseContext())
    {
            var categoryIdParameter = new SqlParameter("@p0", categoryID);
            var pageIndexParameter = new SqlParameter("@p1", pageIndex);
            var pageSizeParameter = new SqlParameter("@p2", Common.PAGE_SIZE);

            var result = context.Database
                .SqlQuery<ProductResult>("GetProductsByCategory @p0, @p1, @p2", categoryIdParameter, pageIndexParameter, pageSizeParameter)
                .ToList();
    }

The result will contain a list of ProductResult objects. 结果将包含ProductResult对象的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM