Wesley Skeen
Wesley Skeen

Reputation: 8285

Can't insert into database using linq

I'm trying to insert a group of people into a database table. I can select from the database without problems but when I try to enter I get

Cannot add an entity with a key that is already in use

I know what this means but why is it happening. I have increment on the tables id. Here's my code.

    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;
        }

The problem happens at the line

People.InsertAllOnSubmit(people);

Is there some special way i have to set up auto-increment with Linq?

Upvotes: 0

Views: 735

Answers (1)

In your dbml designer, click on the column that's the primary key and ensure that the following properties have these values:

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

Since you're not using the dbml designer, you can accomplish it with parameters on a Column attribute for your field property (which will be in addition to the other parameters you will likely have already).

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

Upvotes: 2

Related Questions