ASP.NET MVC DB謫堺ス

ASP.NET MVC CRUD蜃ヲ逅

繧ケ繧ュ繝」繝輔か繝シ繝ォ繝繧」繝ウ繧ー

Scaffolding:雜ウ蝣エ菴懊j
CRUDシCreate/Read/Upadate/Delete) シ夊ソス蜉縲∬ェュ霎シ縲∝、画峩縲∝炎髯、縺ォ髢「縺吶kView縲√さ繝ウ繝医Ο繝シ繝ゥ繝シ繧定ェ蜍穂ス懈舌☆繧

Select

public class ScaffoldingController : Controller
{
縲縲private ContextMember _db = new ContextMember();
縲縲
縲縲public ActionResult Index()
縲縲{
縲縲縲縲return View(_db.MemberDB.ToList());
縲縲}
縲縲
縲縲public ActionResult Details(int? id)
縲縲{
縲縲縲縲if (id == null)
縲縲縲縲{
縲縲縲縲縲縲return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
縲縲縲縲}
縲縲縲縲Member member = _db.MemberDB.Find(id);
縲縲縲縲if (member == null)
縲縲縲縲{
縲縲縲縲縲縲return HttpNotFound();
縲縲縲縲}
縲縲縲縲return View(member);
縲縲}
}

TEST.Models.MyDBEntities myDb = new TEST.Models.MyDBEntities();
var model1 = from m in myDb.MyTable1 select m;
var model2 = from m in myDb.MyTable1 where m.Field1 == 3 select m;

Insert

public class ScaffoldingController : Controller
{
縲縲[HttpPost]
縲縲public ActionResult Create([Bind(Include=
"Id,Name,Email,Birth,Married,Memo")]
Member member)
縲縲{
縲縲縲縲窶サ繝舌う繝ウ繝画ゥ溯スシ唔nclude縺ァ謖螳壹@縺溘ヱ繝ゥ繝。繝シ繧ソ繝シ莉・螟悶rView縺九i貂。縺帙↑縺縲
縲縲縲縲縲蠢鬆医〒縺ッ縺ェ縺縺碁℃螟壹昴せ繝繧」繝ウ繧ー謾サ謦繧帝亟豁「縺ァ縺阪k縲
縲縲縲縲
縲縲縲縲
縲縲縲縲if (ModelState.IsValid)
縲縲縲縲{
縲縲縲縲縲縲db.MemberDB.Add(member);
縲縲縲縲縲縲db.SaveChanges();
縲縲縲縲縲縲return RedirectToAction("Index");
縲縲縲縲}
縲縲縲縲return View(member);
縲縲}
}

TEST.Models.MyDBEntities myDb = new TEST.Models.MyDBEntities();
//model縺ョ譁ー隕丈ス懈
TEST.Models.MyTable1 model = new TEST.Models.MyTable1();
model.Field1 = 4;
model.Field2 = “d”;
model.Field3 = “ddd”;
//Insert蜃ヲ逅
myDb.AddObject(entitySetName: “MyTable1”, entity: model);
myDb.AddToMyTable1(myTable1: model);
窶サ閾ェ蜍慕函謌舌&繧後k繝。繧ス繝繝(荳ュ縺ァ竊羨ddObject()繧貞他縺ウ蜃コ縺)
//菫晏ュ
myDb.SaveChanges();

Delete

TEST.Models.MyDBEntities myDb = new TEST.Models.MyDBEntities();
//謖螳壹@縺殃d縺ァ繝ャ繧ウ繝シ繝峨r謚ス蜃コ
var model = myDb.MyTable1.Where(m => m.Field1 == id).Single();
//蜑企勁
myDb.DeleteObject(entity: model);
//菫晏ュ
myDb.SaveChanges();

Update

TEST.Models.MyDBEntities myDb = new TEST.Models.MyDBEntities();
//謖螳壹@縺殃d縺ァ繝ャ繧ウ繝シ繝峨r謚ス蜃コ
var model = myDb.MyTable1.Where(m => m.Field1 == id).Single();
//螟画峩縺吶k蜀螳ケ繧定ィュ螳
model.Field2 = “D”;
model.Field3 = “DDD”;
//菫晏ュ
myDb.SaveChanges();

Follow me!