ASP.NET MVC & Angularのオンラインチュートリアルに従っていますが、作成者(Sourav Mondal)はEntityを使用してデータベースにクエリします。残念ながら、SQL Server 2000を使用していますが、EFはオプションではありません。以下は、私が転置しようとしていたコードです:エンティティフレームワークを使用したGETからEntity Frameworkなしの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-レスソリューションのための私の現在の憶測で、連絡先は3つのデータベース内のフィールド、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