使用 entity framework 更新 table 中的单行

Update single row in a table using entity framework

我不熟悉在网络表单中使用 EF6。我正在尝试更新 table 中没有 ID 的唯一可用行,它只是应用程序的参数配置 table。

我在窗体视图上有这个更新方法。当我尝试加载项目时它给我错误。我想我在这里做错了,但不确定我需要做什么。我对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 一个 IQueryable 即使你 select 使用 [=15= 只有一条记录]取(1)。您可以使用类似这样的方法作为快速修复:

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

甚至没有 Take as FirstOrDefault select 一行。

取 returns 一个 IQueryable,它 可能 只包含一个项目,但仍然是一个集合。如果您使用 Take(1) 只 select 一条记录,您不妨选择 First(如果您的结果集中有 none,请注意这里)或直接使用 FirstOrDefault

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