使用文本框向基于服务的数据库写入行

Write line to Service-Based Database with textbox

我正在尝试使用文本框逐行创建和写入基于服务的数据库,而没有其他列,只有索引和短语。因此,初学者需要帮助或有用的例子来弄清楚我在这里做错了什么。

所以我做了什么,我的数据库:

CREATE TABLE [dbo].[User]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [Phrase] TEXT NOT NULL
)

在 Id 列 Properties Identity Specification 我已经将(是身份)更改为 True,然后更新 dbo.User [设计],然后刷新到我的 SampleDatabase.mdf,然后显示 Table数据我的选项卡用户,然后我将新项目 LINQ 添加到 SQL 类 到我的项目作为数据类,我已经添加到我的 Program.cs 目录 AppDomain.CurrentDomain.SetData("DataDirectory", System.Environment.CurrentDirectory.Replace("\bin\Debug", "")); 这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XX_7_DATABASE_LOCAL
{
    static class Program
    {
        [STAThread]
        static void Main()
        {   
            AppDomain.CurrentDomain.SetData("DataDirectory", System.Environment.CurrentDirectory.Replace("\bin\Debug", ""));  
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

这是我的 Form1:

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

namespace XX_7_DATABASE_LOCAL
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            User newUser = new User();
            newUser.Phrase = (textBox1.Text);

            DataClassDataContext dbCtx = new DataClassDataContext();
            dbCtx.Users.InsertOnSubmit(newUser);

            try
            {
                dbCtx.SubmitChanges();
                MessageBox.Show("Successful!");
            }
            catch(Exception ex)
            {
                MessageBox.Show("Fail!");
            }        
        }

        private void button2_Click(object sender, EventArgs e) 
        {
            DataClassDataContext dbContext = new DataClassDataContext();
            var getData = (
                from x in dbContext.Users
                select x
                );

            dataGridView1.DataSource = getData;
        }
    }
}

所以我已将消息替换为 MessageBox.Show(ex.Message + ":" + ex.StackTrace);,但不确定这意味着什么以及我必须做什么:

如果 Identity Specification 为 False,则只将一行写入数据库,但对于第二行,我收到此消息:

我作为评论发布,但我认为它实际上是一个答案。 所以我会添加更多的解释:

如果您没有明确告诉数据库您可以通过将 INSERT_IDENTITY 设置为开来向标识列插入值,那么数据库是它的所有者,而不是您。 您可以停止尝试插入用户 ID 并让数据库为您处理它,或者您可以将 INSERT_IDENTITY 设置为 On 并完成这项工作。如果不设置id为Identity列,那么要确保不会有重复的id,否则会崩溃,如第二个错误所述。

我会选择第一个选项,让数据库为您完成。

制作人员:Problems with IDENTITY_INSERT Set to OFF? :-/