我需要帮助。实际上我正在使用带有4.0 .net框架的ADO net,并使用扩展名为.mdf的解决方案资源管理器中的app_data创建一个自己的数据库。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Crudoperations.Models;
using System.Data.Entity;
namespace Crudoperations.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
EmployEntities employContext;
public ActionResult Index()
{
using (var details= new EmployEntities())
{
return View(details.employs.ToList());
}
}
//
// GET: /Employee/Details/5
public ActionResult Details(int id)
{
employContext = new EmployEntities();
employ _TempEmploy = new employ();
_TempEmploy.Id = id;
return View(_TempEmploy);
}
//
// GET: /Employee/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(employ objEmploy)
{
try
{
employContext = new EmployEntities();
employContext.AddToemploys(objEmploy);
employContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
employContext = new EmployEntities();
employ _employ = new employ();
//_employ = ( from Employ
// where ID = id)
return View();
}
[HttpPost]
public ActionResult Edit(int id, employ objEmploy)
{
try
{
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Employee/Delete/5
public ActionResult Delete(int id)
{
employ _TempEmploy = new employ();
return View(_TempEmploy);
}
//
// POST: /Employee/Delete/5
[HttpPost]
public ActionResult Delete(int id, employ objEmploy)
{
try
{
//employContext = new EmployEntities();
//employ _TempEmploy = new employ();
//_TempEmploy.Id = id;
//employ _employ = employContext.Find(_TempEmploy);
employContext.DeleteObject(objEmploy);
employContext.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
public IView detailsModel { get; set; }
}
}
实际上我在使用ID访问数据时遇到问题,即在db上下文中有一个方法“Find(id)”但是在Object上下文中没有这种类型的方法。我必须做什么才能访问数据用于编辑,详细信息和从数据库中删除数据
答案 0 :(得分:0)
您可以使用FirstOrDefault()按ID获取,它将获取第一个匹配的对象。
db.Users.FirstOrDefault(x => x.UserId== Id);
希望,它可能对你有所帮助。有一天。