【问题标题】:Linq Remove an uncommitted entity from an Entity Collection - How do you find the right one?Linq 从实体集合中删除一个未提交的实体 - 你如何找到正确的?
【发布时间】:2013-11-11 15:32:33
【问题描述】:

我的 RadGrid 是从会话状态中保存的实体框架 ICollection 填充的。主键是数据库中的自动递增字段。用户可以将多行添加到网格而不将它们提交到数据库。如果用户在保存之前删除了一行,你如何找到要删除的特定实体?到目前为止,在实际保存数据之前,不会为新行分配主键。

DataContext context = (DataContext)Session["context"];

protected void rgEmployees_DeleteCommand(object source, GridCommandEventArgs e) {
    int MyID = Tools.GetInt((e.Item as GridDataItem).
        OwnerTableView.DataKeyValues[e.Item.ItemIndex]["My_ID"]);
    Employee ee= context.Employee.SingleOrDefault(t => t.ID == MyID); 
    // The problem with above line is that t.ID has not been established yet.
    context.Employee.Remove(ee);
}

【问题讨论】:

    标签: c# entity-framework telerik-grid icollection


    【解决方案1】:

    假设实体将按照您添加它们的顺序,我认为您唯一的选择是通过索引来完成,即

    protected void rgEmployees_DeleteCommand(object source, GridCommandEventArgs e) {
        Employee ee = context.Employee.AsEnumerable().ElementAt(e.Item.ItemIndex); 
        context.Employee.Remove(ee);
    }
    

    【讨论】:

    • 数据确实保持与网格上显示的顺序相同,并且 - 稍作修改 - 此解决方案有效。
    • @Stoertz 请记住,这段代码会将您的完整Employee 表带入内存并使用AsEnumerable,不支持使用EF 的ElementAt
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多