简体   繁体   中英

Update/Edit an Entry in C# CRUD Operations

I am trying to edit a RoleName in my Roles table. Everything is working except I am getting errors that there is no definition for the Entry and the SaveChanges methods. I have using statements for both System.Data.Entity and EntityFramework so I am not sure what the issue is. I'm pretty sure that I have all the correct packages and references.

//Get Edit
[HttpGet]
public ActionResult Edit(Roles model)
{
    return View(); 
}

//Put Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Comtrex_ICU.Models.Roles model, int RoleId, 
    Roles RoleName)
{
    try
    {
        Roles db = new Roles();

        db.Entry(RoleName).State = EntityState.Modified;
        db.SaveChanges();

        return RedirectToAction("RolesIndex");
    }
    catch 
    { 
        return View(); 
    }
}

As you don't appear to be calling them from a repository, Entry and SaveChanges are methods belonging to your EntityFramework Entities.

You're trying to call them from an instance of Roles .

You need to instantiate your Entities as db .

Instead of the following:

Roles db = new Roles();

You should do this (where Entities is the name you've given your entities):

Entities db = new Entities();

You can now find the Role you want to edit by using Find :

var editRole = db.Roles.Find(RoleId);

Then you need to map your edited properties and then make your update.

You should instantiate your entities in the constructor of either the Controller or a service repository rather than each time you need it, but the example above should point you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM