无法使用linq插入数据库

时间:2012-10-17 19:31:25

标签: c# 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设置自动增量?

1 个答案:

答案 0 :(得分:2)

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

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

由于您没有使用dbml设计器,因此您可以使用field属性的参数来完成它(对于您可能已经存在的其他参数)。

[Column(AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
相关问题