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

时间:2009-12-15 17:57:44

标签: asp.net-mvc linq-to-entities

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

LookupTable <- MapTable -> DataTable

我有一个DataTable的自定义绑定器,但无法弄清楚如何创建它来创建MapTable对象。

这可能吗?使用asp.net MVC 1.0和LINQ to Entities。

1 个答案:

答案 0 :(得分:2)

您需要完成两个步骤。 (1)添加新选择的值,(2)删除未选择的值。你需要在LookupTable类中使用这样的方法。

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,而不是整个对象。这更复杂,因为LINQ-to-Entities创建的对象与LINQ-to-SQL略有不同,因为它不公开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);
        }
    }
}