简体   繁体   中英

Accessing un-mapped entities from Entity Framework SqlQuery

I am using Entity Framework, I have an entities class which has 2 fields:

  • Name
  • Description

I have a stored procedure which is returning exact above entities plus an additional entity called TotalRecords . I created a new entity in my above class called TotalRecords and added an attribute [NotMapped] to it.

Now when I call the stored procedure, it does not map to the new entity 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.

Here's how I am calling SqlQuery to execute stored procedure:

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? As I said above, I have just one column extra rest all are being mapped to the database table 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:

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

        public string Description { get; set; }

        public decimal TotalRecords { get; set; }
    }

2) And then call the procedure:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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