如何在没有FK连接的情况下将行从一个表移动到另一个表

时间:2019-06-19 17:31:59

标签: c# entity-framework

我正在做Entity Framework,并且我有一个数据库,其中两个表之间没有连接。我的表单有两个datagridviews,每个datagridviews显示加载时这些表的内容。我也有两个按钮。当我在运动表上选择任何一个单元格(选择整个行)并单击“复制”时,它将数据移动到健康表并将其从运动表中删除。第二个按钮反之亦然。您认为错在哪里?

我尝试删除并添加,似乎出现验证错误。我该如何解决?

public partial class Form1 : Form
{
    SportsAreUsEntities mySports = new SportsAreUsEntities();
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        RefreshGrids();
    }

    private void RefreshGrids()
    {
        var allSport = from eachSport in mySports.SportingItems                          
                       orderby eachSport.SportingItemID ascending
                       select new
                       {
                           eachSport.SportingItemID,
                           eachSport.Name,
                           eachSport.Description,
                           eachSport.QuantityOnHand
                       };

        dataGridSport.DataSource = allSport.ToList();

        var allHealth = from eachHealth in mySports.HealthItems
                        orderby eachHealth.HealthItemID ascending
                        select new
                        {
                            eachHealth.HealthItemID,
                            eachHealth.Name,
                            eachHealth.Description,
                            eachHealth.QuantityOnHand
                        };

        dataGridHealth.DataSource = allHealth.ToList();
    }

    private void moveToHealth_Click(object sender, EventArgs e)
    {
        //Retrieve selected row and id
        var selectedRow = dataGridSport.CurrentRow;
        int selectedID = (int)selectedRow.Cells["SportingItemID"].Value;
        var data2 = new HealthItem();


        var rowToDelete =        (from row in mySports.SportingItems
                                  where row.SportingItemID == selectedID
                                  select row).Single();

        var rowToAdd = (from row in mySports.SportingItems
                           where row.SportingItemID == selectedID
                           select row).Single();
        mySports.SportingItems.Remove(rowToDelete);  //Mark for deletion   
        mySports.HealthItems.Add(data2);
        mySports.SaveChanges();
        RefreshGrids();



    }

0 个答案:

没有答案