質問に対する回答は、SQLサーバーにアクセスするために使用しているデータアクセス技術に大きく依存します。その後、
public bool IsStudentExists(string id)
{
using (var conn = new SqlConnection("some connection string"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM StudentTable WHERE id = @id";
cmd.Parameters.AddWithValue("@id", id);
using (var reader = cmd.ExecuteReader())
{
return reader.Read();
}
}
}
と::
は
public ActionResult LookUpStudentId(string id)
{
if(!IsStudentExists(id))
{
return new RedirectResult("~/Error/NotFound");
}
return View();
}
明らかに、このデータ・アクセス・コードをリポジトリにリファクタリングすることが優れている、あなたはそれについて私たちに語っていないので、ここで、この使用して、プレーンADO.NETを達成する方法を説明しますコントローラが使用しているデータアクセステクノロジに密接に結合されていないようにします。たとえば、あなたが定義してIStudentsRepository
:
public class StudentsController: Controller
{
private readonly IStudentsRepository _repository;
public StudentsController(IStudentsRepository repository)
{
_repository = repository;
}
public ActionResult LookUpStudentId(string id)
{
var student = _repository.GetStudent(id);
if(student == null)
{
return new RedirectResult("~/Error/NotFound");
}
return View(student);
}
}
すべてのこと残されているがconfigure your DI framework of choiceに適切に注入する:あなたは、その後実装し、今お使いのコントローラのアクションは、この抽象化して仕事ができる
public interface IStudentsRepository
{
Student GetStudent(string id);
}
このリポジトリのコントローラへの実装
Entity Framework – user793468
@ user793468を使用しています。これは、EntityFrameworkを使用して示した「IStudentsRepository」を実装するだけです。例えば、あなたがIDを与えられたEFモデルを直接返す 'StudentsRepositoryEF'を持つことができます。 –