代码之家  ›  专栏  ›  技术社区  ›  chris

使用LINQ将嵌套对象保存到实体

  •  1
  • chris  · 技术社区  · 15 年前

    我有一个向用户显示许多复选框的UI,对于每个被选中的UI,我需要在映射表中创建一个条目。

    LookupTable <- MapTable -> DataTable
    

    我有一个用于数据表的自定义绑定器,但无法找到如何让它创建MapTable对象。

    这有可能吗?使用ASP.NET MVC 1.0和LINQ to实体。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Jarrett Meyer    15 年前

    你需要注意两个步骤。(1)添加新选择的值,(2)删除未选择的值。在可查找类中,您需要这样的方法。

    public void SynchronizeDataTables(IEnumerable<DataTable> dataTables)
    {
        // get the current data tables. call ToList() to force and enumeration.
        // without the ToList(), you'll get a "Sequence Changed during Enumeration"
        // error
        var currentDataTables = MapTable.Select(m => m.DataTable).ToList();
    
        // if the table is selected, but not in the data store add it.
        foreach (var dataTable in dataTables)
        {
            if (!currentDataTables.Contains(dataTable))
            {
                MapTables.Add(new MapTable { DataTable = dataTable });
            }
        }
    
        // if the table is in the data store, but not selected, then remove it.
        foreach (var dataTable in currentDataTables)
        {
            if (!dataTables.Contains(dataTable))
            {
                MapTables.Remove(dataTable);
            }
        }
    }
    

    编辑 :执行此操作时,我使用的是Linq to SQL,我只循环使用选定的ID,而不是整个对象。这更复杂,因为LinqToEntities创建的对象与LinqToSQL稍有不同,因为它不公开FK标识。轻微修改如下:

    public void SynchronizeDataTables(IEnumerable<int> dataTableIds)
    {
        // get the current data tables. call ToList() to force and enumeration.
        // without the ToList(), you'll get a "Sequence Changed during Enumeration"
        // error
        var currentDataTableIds = MapTable.Select(m => m.DataTable.Id).ToList();
    
        // if the table is selected, but not in the data store add it.
        foreach (var dataTableId in dataTableIds)
        {
            if (!currentDataTableIds.Contains(dataTableId))
            {
                var dataTable = ???; // some method to fetch data table with ID = dataTableId
                MapTables.Add(new MapTable { DataTable = dataTable });
            }
        }
    
        // if the table is in the data store, but not selected, then remove it.
        foreach (var dataTable in currentDataTableIds )
        {
            if (!dataTableIds.Contains(dataTableId ))
            {
                var dataTable = ???; // some method to fetch data table with ID = dataTableId
                MapTables.Remove(dataTable);
            }
        }
    }