我試圖將一羣人插入到數據庫表中。我可以從數據庫沒有問題的選擇,但是當我試圖進入我得到無法使用linq插入數據庫
Cannot add an entity with a key that is already in use
我知道這意味着什麼,但爲什麼它的發生。我有增量表上的ID。這是我的代碼。
public static List<Person> GetPeople(DataContext db)
{
List<Person> people = new List<Person>();
Table<Person> People = db.GetTable<Person>();
for (int i = 0; i < 5; i++)
{
Person pers = new Person();
pers.PersFirstName = "Wesley " + i;
//pers.PersId is the primary key that I want to auto-increment and not have to set it here
people.Add(pers);
}
People.InsertAllOnSubmit(people);
People.Context.SubmitChanges();
IQueryable<Person> query =
from person in People
select person;
return people;
}
的問題發生在該行
People.InsertAllOnSubmit(people);
是否有一些特殊的辦法,我必須設置自動遞增的LINQ?
您必須設置數據庫增加標識值。你有沒有設置'PersonId'是主鍵? – Kai
是的,我已經完成了這個 –
您是否在生成映射之前設置了pk?如果不重新創建映射文件。 – Kai