简体   繁体   English

使用实体框架更新表中的单行

[英]Update single row in a table using entity framework

I'm new at using EF6 in webforms. 我是在Webforms中使用EF6的新手。 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. 我正在尝试更新表中唯一没有ID的行,它只是应用程序的参数配置表。

I have this update method on the formview. 我在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. 我对linq一无所知。

Error 11 Cannot implicitly convert type 'System.Linq.IQueryable' to 'InventarioCiclico.xInventarioConfigs'. 错误11无法将类型'System.Linq.IQueryable'隐式转换为'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 存在显式转换(是否缺少强制转换?)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) . 就拿一个IQueryable即使你通过采取(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 as FirstOrDefault也会选择一行。

Take returns an IQueryable which might only contain one item but still is a collection of sorts. Take返回一个IQueryable,它可能只包含一个项目,但仍然是各种集合。 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 如果使用Take(1)仅选择一条记录,则最好直接选择First(如果结果集中没有记录,请谨慎选择)或FirstOrDefault

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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