WakaChewbacca WakaChewbacca - 4 months ago 17
AngularJS Question

Translating a GET with Entity Framework to a GET without Entity Framework

I am following a tutorial online for ASP.NET MVC & Angular, but the author(Sourav Mondal) uses Entity to query the database. Unfortunately, I am using SQL Server 2000, and EF is not an option. The following is the code which I am attempting to transpose:

// GET: /Data/
//For fetch Last Contact
public JsonResult GetLastContact()
{
Contact c = null;
//here MyDatabaseEntities our DBContext
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
c = dc.Contacts.OrderByDescending(a => a.ContactID).Take(1).FirstOrDefault();
}
return new JsonResult { Data = c, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}


This is my current speculation for an EF-less solution, supposing the Contacts have three fields in the database,
ContactID
,
Name
, and
Password
:

Models/Contact.cs
class:

public class Contact
{
public string Name { get; set; }
public string Password { get; set; }
}


Controllers/DataController.cs
,
GetLastContact()
:

public class DataController : Controller
{
// GET: /Data/
public JsonResult GetLastContact()
{

Contact c = null;
using (SqlConnection cnxn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString))
{
using (SqlCommand sqlQuery = new SqlCommand("SELECT TOP 1 ContactID FROM Northwind ORDER BY ContactID DESC "))
{
cnxn.Open();
SqlDataReader reader = sqlQuery.ExecuteReader();

while (reader.Read())
{
string contact_ID = (string)reader["ContactID"];
string first_name = (string)reader["Name"];
string password = (string)reader["Password"];
}
// Some magic here

reader.Close();
cnxn.Close();
}
}

return new JsonResult { Data = c, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}


And Sourav's Angular code:

angular.module('MyApp') //extending from previously created angular module in the previous part
.controller('Part2Controller', function ($scope, ContactService) { //inject ContactService
$scope.Contact = null;
ContactService.GetLastContact().then(function (d) {
$scope.Contact = d.data; // Success
}, function () {
alert('Failed'); // Failed
});
})
.factory('ContactService', function ($http) { // here I have created a factory which is a populer way to create and configure services
var fac = {};
fac.GetLastContact = function () {
return $http.get('/Data/GetLastContact');
}
return fac;
});


I feel like although my solution is probably spaghetti, it cannot be too far off from working. Any little nudge anyone could give this code would be awesome! Or any constructive advice as to how one should proceed in stripping Entity of its Entity.

Answer
// Some magic here
c = new Contact
{
  Name = first_name,
  Password = password
};
// end of magic