我正在关注ASP.NET MVC & Angular的在线教程,但作者(Sourav Mondal)使用实体来查询数据库。不幸的是,我正在使用SQL Server 2000,而EF不是一个选项。以下是我在尝试转码:将实体框架的GET转换为不带实体框架的GET
// 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 };
}
这是我的EF-更少的解决方案,当前的投机,假设联系人在数据库中具有三个字段,ContactID
,Name
和Password
:
Models/Contact.cs
类:
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 };
}
}
而且Sourav的角码:
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;
});
我觉得虽然我的解决方案可能是意大利面,也不能太离谱的工作。任何人都可以给这个代码任何小推动都会很棒!或者有关如何进行剥离其实体的实体的任何建设性意见。
当然!我也忘记声明用于循环外的字段的字符串。谢谢! – WakaChewbacca