0

我遇到了一个问题,其中涉及使用 linq 查询的外键。就像这样,我有 2 个表,“站”和“位置”。它们使用它们的主要链接到另一个表“locationstation”。我需要从“站”表中获取站名和“位置”表中的位置。

这是我用来连接所有 3 个表并在数据网格视图中显示的代码。

private void Create_LS_Load(object sender, EventArgs e)
    {
        using (testEntities Setupctx = new testEntities())
        {
            var storeStation = (from SLS in Setupctx.locationstations
                                        join station s in Setupctx.stations on SLS.idStation equals s.idstations
                               select s.Station1).Distinct().ToList();                                   
            foreach (var LocationStation in storeStation)
            {
                cbStation.Items.Add(LocationStation);
            }

            var storeLocation = (from SLS in Setupctx.locationstations
                                join location l in Setupctx.locations on SLS.idLocation equals l.idlocation
                                select l.Location1).Distinct().ToList();                                      
            foreach (var LocationStation1 in storeLocation)
            {
                cbLocation.Items.Add(LocationStation1);
            }
        }
    }

在完成显示到数据网格视图后,我将站名和位置名绑定到两个相应的组合框中。这是我绑定的代码。

string selectStation = cbStation.SelectedItem.ToString();
            string selectLocation = cbLocation.SelectedItem.ToString();

之后,我需要通过使用组合框选择站点和位置来创建新的“locationstation”。我怎么做?“locationstation”下的列名仍然是“station”和“location”的id 如何实际创建新的locationstation?我迷路了。

任何帮助将不胜感激。

4

1 回答 1

0

You're close - you just need to grab the whole selected object when you're done - not just the name as a string:

Station selectedStation = cbStation.SelectedItem as Station;
Location selectedLocation = cbLocation.SelectedItem as Location;

Now, you have access to all the necessary properties on that object - you can extract the Name, the ID and whatever else you might need to build up your new entity (or entities).

于 2012-07-16T08:39:17.343 回答