1

With MVC4, I'm having some trouble inserting new rows into my database (SQL Compact). I'm building the rows from raw text (tab separated) like this:

                while (reader.Peek() != -1)
            {
                newRow = Cos.Create();
                line = reader.ReadLine().Split('\t');
                for (int i = 0; i < header.Count(); i++)
                {
                    switch (header[i])
                    {
                        case "CompanyName":
                            newRow.CompanyName = line[i];
                            break;
                        case "City":
                            newRow.City = line[i];
                            break;
                        case "Country":
                            newRow.Country = line[i];
                            break;
                        default:
                            return "A column was found with an unacceptable value - " + header[i] + " - No changes have been made.";
                    }
                }
                this.Cos.Add(newRow);
            }
        this.SaveChanges();

My table has an Id column, which is set to be: int, Unique, Primary Key, and Identity (seed:1, increment:1). The problem is that SQL rejects the statements generated by "this.SaveChanges()" because the Id values of all the rows I generate are 0.

Is there a way for me to have SQL assign a unique Id to each row upon insertion? It was my understanding that this way the purpose of Identities.

My model simply looks like this:

public class CoDB{
        public string CompanyName { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public int Id { get; set; }
}

And CoDBContext defines:

public DbSet<CoDB> Cos {get; set;}

Thank you so much for any help! -Zach

Zach
  • 316
  • 4
  • 14

1 Answers1

0

Sounds like your trying to set the value of an auto identity field, which you shouldn't. See if this helps: Autonumber with Entity Framework

Community
  • 1
  • 1
ThatSteveGuy
  • 1,085
  • 7
  • 11