报错:无法将类型"System.Data.EntityState"隐式转换为"System.Data.Entity.EntityState"

 报错:无法将类型"System.Data.EntityState"隐式转换为"System.Data.Entity.EntityState"

原因一:

 

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

是否引用了System.Data.Entity   是则:db.Entry<UserInfo>(entity).State =EntityState.Deleted;

                                               否则加上db.Entry<UserInfo>(entity).State = System.Data.EntityState.Deleted;

加上命名空间

原因二:

 

出错语句停留在:DataContext.Entry(entity).State = EntityState.Modified; 
从语法上看没有什么错误。DataContext是在Model层通过添加edmx自动生成的,而出错语句所在的数据层安装了最新版的Entity Framework,我们知道:在edmx中创建实体导入数据库的时候,VS也会为我们自动装上Entity Framework,是否此处的EF版本和数据层不一样呢?

 

解决方法

 

先卸载EF:Uninstall-Package EntityFramework -Force 
在安装EF5.0:Install-Package EntityFramework –Version 5.0.0

 

转载于:https://www.cnblogs.com/luwei19911206/p/4624046.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建了一个使用实体框架和SQL Server Express LocalDB来存储和显示数据的简单Web应用程序. 实现了基本的CRUD和排序、筛选、分页及分组功能. using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using ContosoUniversity.DAL; using ContosoUniversity.Models; using PagedList; namespace ContosoUniversity.Controllers { public class StudentsController : Controller { private SchoolContext db = new SchoolContext(); // GET: Students //public ActionResult Index() //{ // return View(db.Students.ToList()); //} /* step1 public ActionResult Index(string sortOrder) { ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; var students = from s in db.Students select s; switch (sortOrder) { case "name_desc": students = students.OrderByDescending(s => s.LastName); break; case "Date": students = students.OrderBy(s => s.EnrollmentDate); break; case "date_desc": students = students.OrderByDescending(s => s.EnrollmentDate); break; default: students = students.OrderBy(s => s.LastName); break; } return View(students.ToList()); } */ /*step2 public ViewResult Index(string sortOrder, string searchString) { ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; var students = from s in db.Students select s; if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.Contains(searchString) || s.FirstMidName.Contains(searchString)); } switch (sortOrder) { case "name_desc": students = students.OrderByDescending(s => s.LastName); break; case "Date": students = students.OrderBy(s => s.EnrollmentDate); break; case "date_desc": students = students.OrderByDescending(s => s.EnrollmentDate); break; default: students = students.OrderBy(s => s.LastName); break; } return View(students.ToList()); } */ public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page) { ViewBag.CurrentSort = sortOrder; ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : ""; ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date"; if (searchString != null) { page = 1; } else { searchString = currentFilter; } ViewBag.CurrentFilter = searchString; var students = from s in db.Students select s; if (!String.IsNullOrEmpty(searchString)) { students = students.Where(s => s.LastName.Contains(searchString) || s.FirstMidName.Contains(searchString)); } switch (sortOrder) { case "name_desc": students = students.OrderByDescending(s => s.LastName); break; case "Date": students = students.OrderBy(s => s.EnrollmentDate); break; case "date_desc": students = students.OrderByDescending(s => s.EnrollmentDate); break; default: // Name ascending students = students.OrderBy(s => s.LastName); break; } int pageSize = 6; int pageNumber = (page ?? 1); return View(students.ToPagedList(pageNumber, pageSize)); } // GET: Students/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = db.Students.Find(id); if (student == null) { return HttpNotFound(); } return View(student); } // GET: Students/Create public ActionResult Create() { return View(); } // POST: Students/Create // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "LastName,FirstMidName,EnrollmentDate")] Student student) { try { if (ModelState.IsValid) { db.Students.Add(student); db.SaveChanges(); return RedirectToAction("Index"); } } catch(DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); } return View(student); } // GET: Students/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Student student = db.Students.Find(id); if (student == null) { return HttpNotFound(); } return View(student); } // POST: Students/Edit/5 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性,有关 // 详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,LastName,FirstMidName,EnrollmentDate")] Student student) { if (ModelState.IsValid) { db.Entry(student).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(student); } // GET: Students/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //if (saveChangesError.GetValueOrDefault()) { // ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator."; //} Student student = db.Students.Find(id); if (student == null) { return HttpNotFound(); } return View(student); } // POST: Students/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Student student = db.Students.Find(id); db.Students.Remove(student); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
创建一个基本的.net core API项目并实现增删改查可以按照以下步骤进行: 1. 打开Visual Studio 2019,点击"Create a new project",选择.NET Core > ASP.NET Core Web Application,并在下拉框中选择API,然后点击"Create"按钮。 2. 在新建项目的对话框中,填写项目名称和存储路径,然后点击"Create"按钮。 3. 在创建的项目中,打开Startup.cs文件,在ConfigureServices方法中添加如下代码,以启用EFCore: ``` services.AddDbContext<YourDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); ``` 4. 在Configure方法中添加以下代码来启用MVC: ``` app.UseMvc(); ``` 5. 在项目中添加实体类,例如: ``` public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` 6. 在项目中添加DbContext类,例如: ``` public class YourDbContext : DbContext { public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } } ``` 7. 添加控制器类,例如: ``` [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { private readonly YourDbContext _context; public ProductsController(YourDbContext context) { _context = context; } // GET: api/Products [HttpGet] public async Task<ActionResult<IEnumerable<Product>>> GetProducts() { return await _context.Products.ToListAsync(); } // GET: api/Products/5 [HttpGet("{id}")] public async Task<ActionResult<Product>> GetProduct(int id) { var product = await _context.Products.FindAsync(id); if (product == null) { return NotFound(); } return product; } // POST: api/Products [HttpPost] public async Task<ActionResult<Product>> PostProduct(Product product) { _context.Products.Add(product); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); } // PUT: api/Products/5 [HttpPut("{id}")] public async Task<IActionResult> PutProduct(int id, Product product) { if (id != product.Id) { return BadRequest(); } _context.Entry(product).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } // DELETE: api/Products/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteProduct(int id) { var product = await _context.Products.FindAsync(id); if (product == null) { return NotFound(); } _context.Products.Remove(product); await _context.SaveChangesAsync(); return NoContent(); } } ``` 这样,你就可以在控制器类中实现基本的增删改查操作。注意,这里只是一个简单的示例,你可以根据实际需求来修改和完善代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值