簡體   English   中英

使用實體框架更新表中的單行

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

我是在Webforms中使用EF6的新手。 我正在嘗試更新表中唯一沒有ID的行,它只是應用程序的參數配置表。

我在formview上有此更新方法。 當我嘗試加載項目時,它給了我錯誤。 我認為我在這里做錯了,但是不確定我需要做什么。 我對linq一無所知。

錯誤11無法將類型'System.Linq.IQueryable'隱式轉換為'InventarioCiclico.xInventarioConfigs'。 存在顯式轉換(是否缺少強制轉換?)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();

        }
    }

就拿一個IQueryable即使你通過采取(1)只選擇一個記錄返回。 您可以使用以下方法作為快速解決方案:

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

甚至沒有Take as FirstOrDefault也會選擇一行。

Take返回一個IQueryable,它可能只包含一個項目,但仍然是各種集合。 如果使用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