Implement the Entity Framework in the Web API

trx

I am Newbie to ASP.NET, created the MVC Framework Web API which accepts the array of ID's as input parameter and queries the Oracle DB, this should return the result in the JSON format.Our query is like

SELECT STCD_PRIO_CATEGORY_DESCR.DESCR AS CATEGORY, 
      STCD_PRIO_CATEGORY_DESCR.SESSION_NUM AS SESSION_NUMBER, 
      Trunc(STCD_PRIO_CATEGORY_DESCR.START_DATE) AS SESSION_START_DATE
      from STCD_PRIO_CATEGORY 
      where STCD_PRIO_CATEGORY_DESCR.STD_REF IN(X,Y,Z)

where X,Y,Z are the values we will be passing as input parameters

I created the API controller as

  public class PDataController : ApiController
   {
    public HttpResponseMessage Getdetails([FromUri] string[] id)
    {
     List<OracleParameter> prms = new List<OracleParameter>();
     string connStr = ConfigurationManager.ConnectionStrings["PDataConnection"].ConnectionString;
     using (OracleConnection dbconn = new OracleConnection(connStr))
    {
    var inconditions = id.Distinct().ToArray();
    var srtcon = string.Join(",", inconditions);
    DataSet userDataset = new DataSet();
    var strQuery = @"SELECT STCD_PRIO_CATEGORY_DESCR.DESCR AS CATEGORY, 
      STCD_PRIO_CATEGORY_DESCR.SESSION_NUM AS SESSION_NUMBER, 
      Trunc(STCD_PRIO_CATEGORY_DESCR.START_DATE) AS SESSION_START_DATE          
      from STCD_PRIO_CATEGORY 
      where STCD_PRIO_CATEGORY_DESCR.STD_REF IN(";
    StringBuilder sb = new StringBuilder(strQuery);
     for(int x = 0; x < inconditions.Length; x++)
         {
           sb.Append(":p" + x + ",");
           OracleParameter p = new OracleParameter(":p" + x,OracleDbType.NVarchar2);
           p.Value = inconditions[x];
           prms.Add(p);
         }
    if(sb.Length > 0) sb.Length--;
    strQuery = sb.ToString() + ")"; 
    using (OracleCommand selectCommand = new OracleCommand(strQuery, dbconn))
      {
       selectCommand.Parameters.AddRange(prms.ToArray());
         using (OracleDataAdapter adapter = new OracleDataAdapter(selectCommand))
        {
            DataTable selectResults = new DataTable();
            adapter.Fill(selectResults);
            var returnObject = new { data = selectResults };
            var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
            ContentDispositionHeaderValue contentDisposition = null;
            if (ContentDispositionHeaderValue.TryParse("inline; filename=ProvantisStudyData.json", out contentDisposition))
            {
                response.Content.Headers.ContentDisposition = contentDisposition;
            }
             return response;
}}}}}}

It works perfectly and returns the result as {"data":[{"CATEGORY":"Internal Study","SESSION_NUMBER":7,"SESSION_START_DATE":"2015-02-13T00:00:00"}]}

But would like to implement the entity framework here by using the Model and the DBContext.I created the model class and the DataContext Class as follows

namespace PSData.Models
{ public class StudyDataModel
{ [Key]
public string CATEGORY { get; set; }
public int SESSION_NUMBER { get; set; }
public DateTime SESSION_START_DATE { get; set; }
}}

And

namespace PSData.Models
{
 public class StudyDataContext:DbContext
 {
 public DbSet<StudyDataModel> details { get; set; }
 }}

I am not sure how to implement them in the controller. When I tried to create the Controller using Web API 2 Controller with actions,using Entity Framework selected both the Model Class and the DB Context Class it creates controller with

 private StudyDataContext db = new StudyDataContext();
 // GET: api/StdData
 public IQueryable<StudyDataModel> Getdetails()

I am not sure how to proceed as the return type is the HttpResponseMessage in my other Controller where I am returning the JSON message. Any help is greatly appreciayed

Shyju

You do not need to explicitly convert it to json format. The content negotiation module and media formatter will take care of converting the data to the needed format (XML/JSON) based on the request. By default it returns JSON.

Assuming you have a DTO class like this

public class CategoryDto
{
  public string Category { get; set; }
  public int SessionNumber { get; set; }
  public DateTime SessionStartDate { get; set; }
}

and in your action method, you can use Request.CreateResponse method.

public HttpResponseMessage Get()
{
   var db = new StudyDataContext();
   var data = db.details.Select(x => new CategoryDto { 
                                                    Category = x.Category,
                                                    SessionStartDate  = x.SessionStartDate,
                                                    SessionNumber = x.SessionNumber }
                               ).ToList();
   return Request.CreateResponse(HttpStatusCode.OK, data);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Architecture: entity framework Web Api

From Dev

Error while publishing a Web API with Entity Framework

From Dev

Pagination using Entity Framework through Web API

From Dev

Pagination using Entity Framework through Web API

From Dev

Entity Framework Many to many Web API Get

From Dev

Web API with separate entity framework data layer

From Dev

Using Web API by Generating Entity Framework scaffolding API Controller Error

From Dev

Entity Framework web or Entity Object

From Dev

ASP Web API Controller with Entity Framework very slow and strange results

From Dev

Resolving Entity Framework's AccountController with Simple Injector and Web API

From Dev

Web API integrated with Entity framework 5 with database first approach

From Dev

Entity Framework and Web API/REST - Joining to list properties

From Dev

Which Versions of Entity Framework are Compatible with Web API 2?

From Dev

Entity Framework disposing with async controllers in Web api/MVC

From Dev

Entity Framework and Web API/REST - Joining to list properties

From Dev

Web ApI Entity Framework (Code First) Value not appearing in database

From Dev

ASP Web API Controller with Entity Framework very slow and strange results

From Dev

Search data in asp.net web api and Entity Framework

From Dev

Trouble connecting to my database with entity framework c# web api

From Dev

ASP.NET Web API 2 CRUD Operation with Entity Framework

From Dev

Entity Framework DB-First, implement inheritance

From Dev

How do I implement versioning with Entity Framework

From Dev

Specify entity framework context implement IDisposable with Ninject

From Dev

.NET Entity Framework, clean way to implement it?

From Dev

Correct way to implement async Entity Framework repository

From Dev

Entity Framework DB-First, implement inheritance

From Dev

.NET Entity Framework, clean way to implement it?

From Dev

How to implement SQL where in for entity framework 6

From Dev

Specify entity framework context implement IDisposable with Ninject

Related Related

  1. 1

    Architecture: entity framework Web Api

  2. 2

    Error while publishing a Web API with Entity Framework

  3. 3

    Pagination using Entity Framework through Web API

  4. 4

    Pagination using Entity Framework through Web API

  5. 5

    Entity Framework Many to many Web API Get

  6. 6

    Web API with separate entity framework data layer

  7. 7

    Using Web API by Generating Entity Framework scaffolding API Controller Error

  8. 8

    Entity Framework web or Entity Object

  9. 9

    ASP Web API Controller with Entity Framework very slow and strange results

  10. 10

    Resolving Entity Framework's AccountController with Simple Injector and Web API

  11. 11

    Web API integrated with Entity framework 5 with database first approach

  12. 12

    Entity Framework and Web API/REST - Joining to list properties

  13. 13

    Which Versions of Entity Framework are Compatible with Web API 2?

  14. 14

    Entity Framework disposing with async controllers in Web api/MVC

  15. 15

    Entity Framework and Web API/REST - Joining to list properties

  16. 16

    Web ApI Entity Framework (Code First) Value not appearing in database

  17. 17

    ASP Web API Controller with Entity Framework very slow and strange results

  18. 18

    Search data in asp.net web api and Entity Framework

  19. 19

    Trouble connecting to my database with entity framework c# web api

  20. 20

    ASP.NET Web API 2 CRUD Operation with Entity Framework

  21. 21

    Entity Framework DB-First, implement inheritance

  22. 22

    How do I implement versioning with Entity Framework

  23. 23

    Specify entity framework context implement IDisposable with Ninject

  24. 24

    .NET Entity Framework, clean way to implement it?

  25. 25

    Correct way to implement async Entity Framework repository

  26. 26

    Entity Framework DB-First, implement inheritance

  27. 27

    .NET Entity Framework, clean way to implement it?

  28. 28

    How to implement SQL where in for entity framework 6

  29. 29

    Specify entity framework context implement IDisposable with Ninject

HotTag

Archive