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 に答える