0

我正在尝试将一组人插入到数据库表中。我可以毫无问题地从数据库中进行选择,但是当我尝试输入时,我得到了

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 设置自动增量吗?

4

1 回答 1

2

在您的 dbml 设计器中,单击作为主键的列并确保以下属性具有这些值:

Auto Generated Value: True
Auto-Sync: OnInsert
Primary Key: True

由于您没有使用 dbml 设计器,因此您可以使用字段属性的 Column 属性上的参数来完成它(这将是您可能已经拥有的其他参数的补充)。

[Column(AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
于 2012-10-17T19:44:47.420 回答