【问题标题】:Unable to insert records in SQLite database using Entity Framework 5无法使用 Entity Framework 5 在 SQLite 数据库中插入记录
【发布时间】:2012-07-18 10:47:02
【问题描述】:

我尝试使用 ADO.NET Entity Framework 5 使用 SQLite 数据库,我能够连接到 SQLite 数据库并能够从数据库中的表中查询记录。但是当我尝试将记录插入表中时,SaveChanges 会引发异常

"An error occurred while updating the entries. See the inner exception for details."

代码如下:

var connectionStr = string.Format("data source={0};Version=3;UseUTF16Encoding=True;",
    fileName);
var conn = new SQLiteConnection(connectionStr);

this.personDataContext = new PersonDataContext(conn);

var persons = (from person in File.ReadAllLines(fileName)
               let p = person.Split(new[] { ',', ' ' },
                                    StringSplitOptions.RemoveEmptyEntries)
               select new Person
               {
                   ID = Convert.ToInt32(p[0]),
                   Name = p[1],
                   Address = p[2],
                   MobNo = Convert.ToInt32(p[3]),
                   PhNo = Convert.ToInt32(p[4]),
                   Designation = p[5]
               }).ToList();

if (this.personDataContext != null && this.personDataContext.Persons != null)
{
    foreach (var person in persons)
    {
      this.personDataContext.Persons.Add(person);
    }

    var saveFailed = false;

    do
    {
        try
        {
            this.personDataContext.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            saveFailed = true;
            ex.Entries.Single().Reload();
        }
    }
    while (saveFailed);
}

当我检查内部异常时,它说未定义主键。所以,在表中定义了主键后,每次都会出现同样的异常。

我附上了示例应用程序here。先使用 Open Db 打开示例数据库,然后尝试导入 CSV 文件。

我正在使用 Code First 方法,其中我设计了一个 Model 类并将其与 SQLite 数据库中的表连接。

请帮助解决问题。谢谢!

【问题讨论】:

  • 您能否更新您的问题并提供更多详细信息?您的创建代码如何,错误确切的错误消息是什么?有一个重现解决方案很好,但只有极少数用户会下载它。并请考虑后来的用户:当其他人遇到类似问题时,他们会如何找到您的问题。
  • 你能发布内部异常消息的确切文本吗?
  • 内部异常是:- {"由于违反约束而中止\r\nPerson.ID 可能不为 NULL"}。我不明白为什么这段代码在 SQLite 中表现得很奇怪,因为代码代码在 SQL Server 上运行良好。

标签: sqlite entity-framework-4.1


【解决方案1】:

尝试在Person 类中为您的关键属性禁用数据库生成的身份:

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }

在我看来,您似乎想要手动提供键值 (ID = Convert.ToInt32(p[0])),但 EF 不会将此值发送到数据库,因为默认情况下它希望在数据库中生成 ID 值。如果它没有在数据库中生成,则会出现异常。通过将DatabaseGeneratedOption 设置为None,EF 将获取您提供的值并在 INSERT 语句中将其发送到数据库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    相关资源
    最近更新 更多