1

I did try to make sample by EF5 and MySQL.

[Table("agency")]
class Agency
{
    [Key]
    [Required]
    public int agency_id { get; set; }
    public string name { get; set; }
}

class MyContext : DbContext
{
    public DbSet<Agency> Agency { get; set; }
}

class Sample
{
    public static void Main()
    {
        using (var db = new MyContext())
        {
            var query = from x in db.Agency select x.agency_id;
            var new_num = query.DefaultIfEmpty<int>().Max(p => p == null ? 0 : p);

            new_num++;

            Agency a = new Agency
            {
                agency_id = new_num,
                name = "Test"
            };

            db.Agency.Add(a);
            db.SaveChanges();
        }
    }
}

At first. It was successful.
But at second time, It threw the exception in db.SaveChanges().
{"Duplicate entry '0' for key 'PRIMARY'"}

With the thrown exception, I traced variable.
agency_id had '1', certainly.

What was wrong?

Update 1

Update 2

!!!!???????????????????????????

Community
  • 1
  • 1
Jaime
  • 2,148
  • 1
  • 16
  • 19

4 Answers4

2

Ok, I found a solution.

https://stackoverflow.com/a/6752692/415682

DatabaseGeneratedAttribute is point!!!

[Table("agency")]
class Agency
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int my_id { get; set; }
    public string name { get; set; }
}
Community
  • 1
  • 1
Jaime
  • 2,148
  • 1
  • 16
  • 19
0

Try this one:

        int new_num = 0;
        if (db.Agency.Any())
        {
            new_num = db.Agency.Max(a => a.agency_id) + 1;
        }
Denys Denysenko
  • 7,598
  • 1
  • 20
  • 30
0

Probably the mapping is not correct. Make sure the name of the id in the database is 'agency_id'.

L-Four
  • 13,345
  • 9
  • 65
  • 109
0

Why are you manually incrementing your primary key? I see you are using MySQL. Just make it an Auto Incremented column and be done with it. See here: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Try this and stop manually assigning agency_id... It may solve your problems.

Matt
  • 6,787
  • 11
  • 65
  • 112