简体   繁体   中英

Update single row in a table using entity framework

I'm new at using EF6 in webforms. I'm trying to update the only row available in a table that has no ID, it's just a parameters configurations table for the application.

I have this update method on the formview. It gives me error when i try to load the item. I think i'm doing it wrong here though but not sure what do i need to do. I no nothing about linq.

Error 11 Cannot implicitly convert type 'System.Linq.IQueryable' to 'InventarioCiclico.xInventarioConfigs'. An explicit conversion exists (are you missing a cast?) C:\\Users\\A0H79224\\Documents\\Visual Studio 2013\\Projects\\InventarioCiclico\\InventarioCiclico\\Account\\Admin\\ConfigurarInventario.aspx.cs 73 20 InventarioCiclico

 // The id parameter name should match the DataKeyNames value set on the control
    public void fvInventarioConfigs_UpdateItem(xInventarioConfigs configs)
    {

        InventarioCiclico.xInventarioConfigs item = configs;

        InventarioCiclicoContext context = new InventarioCiclicoContext();

        // Load the item here, e.g. item = MyDataLayer.Find(id);
        item = (from c in context.xInventarioConfigs select c).Take(1);
        if (item == null)
        {
            // The item wasn't found
            ModelState.AddModelError("", String.Format("Item with id was not found"));
            return;
        }

        TryUpdateModel(item);
        if (ModelState.IsValid)
        {
            context.SaveChanges();
            // Save changes here, e.g. MyDataLayer.SaveChanges();

        }
    }

Take returns an IQueryable even if you select only one record by using Take(1) . You can use something like this as a quick fix:

item = (from c in context.xInventarioConfigs select c).Take(1).FirstOrDefault();

Or even without Take as FirstOrDefault selects one row anyway.

Take returns an IQueryable which might only contain one item but still is a collection of sorts. If you select only one record by using Take(1) you might as well go for First (careful here if there is none in your result set) or FirstOrDefault directly

item = (from c in context.xInventarioConfigs select c).FirstOrDefault();

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