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);
}
内部例外を確認すると、主キーが定義されていないと表示されます。したがって、主キーをテーブルに定義した後、毎回同じ例外が発生します。
ここにサンプル アプリケーションを添付します。最初に Open Db を使用してサンプル データベースを開き、次に CSV ファイルのインポートを試みます。
Model クラスを設計し、それを SQLite データベースのテーブルに接続する Code First アプローチを使用しています。
問題の解決にご協力ください。ありがとう!