为什么我的订单 Table 没有变化,而它显示了我的 DataGridView 中的变化?

Why there is no change in my order Table while it shows the change in my DataGridView?

我想使用 Linq 操作本地数据库 northWind 中的数据

我遵循了 MSDNCreating and connecting 的流程

我创建了 NorthWind.dbml linq 文件并将两个 table 放入其中:

之后,我在我的表单中编写了这段代码来检索数据并将新数据添加到我的数据库中:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LinqToSql_Ders
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            show();
            comboBoxItems();
        }
        NorthWindDataContext db = new NorthWindDataContext();
        private void show()
        {

            var linqCommand = from order in db.Orders
                              join cust in db.Customers
                              on order.CustomerID equals cust.CustomerID
                              select new
                              {
                                  order.OrderID,
                                  order.OrderQuantity,
                                  order.OrderDate,
                                  cust.CustomerID,                                 
                              };
            dataGridView1.DataSource = linqCommand;
        }

        void comboBoxItems()
        {
            var linqCommand = from cust in db.Customers
                              select cust;
            orderCombBox.DataSource = linqCommand;
            orderCombBox.ValueMember = "CustomerID";
            orderCombBox.DisplayMember = "CustomerID";
        }
        private void addButton_Click(object sender, EventArgs e)
        {
            Order ord = new Order();
            ord.OrderID = int.Parse(orderIDTextField.Text);
            ord.OrderQuantity = int.Parse(nudquantityfield.Value.ToString());
            ord.CustomerID = orderCombBox.SelectedValue.ToString();
            ord.OrderDate = dateTimePicker.Value;
            db.Orders.InsertOnSubmit(ord);
            db.SubmitChanges();
            show();
        }

    }
}

它以正确的方式显示已经添加的列

当我添加新项目时,dataGridView 显示它已添加 但是当我查看 table "order" 数据时,它什么也没显示(没有添加任何新记录)

我使用的代码有没有问题,尤其是DB部分:

db.Orders.InsertOnSubmit(ord);
db.SubmitChanges();

或者我该如何解决我的问题?

您的代码工作正常,但您无法使用 Visual Studio 数据 table 编辑器从数据库中获取最新值。

每次您 运行 应用程序时,数据库文件都会被复制到 bin 文件夹中。您可以通过在解决方案资源管理器中选择数据库文件并将 "Copy to output directory" 选项更改为 "Copy if newer" 或(甚至更好)更改为 "Do not copy"(在第一个 运行 之后)来禁用此行为。以后如果要修改数据库的结构就得把bin目录下的数据库文件复制粘贴到项目目录下,在Visual Studio编辑器下修改,再复制回来。

最好的选择是将数据库文件放在项目之外,并将有效的连接字符串(在配置文件中)设置到这个新位置。

有用的链接: