2
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AdminID { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string Passwort { get; set; }
public DateTime ErstelltAm { get; set; }

The table is constructed almost correct but the primary key is not auto incremented. How do i fix this?

Sknecht
  • 984
  • 2
  • 11
  • 31
  • 1
    `[Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int AdminID{ get; set; }` – wiretext Sep 04 '15 at 07:56
  • 1
    Sorry but that did not help. Same result as before. – Sknecht Sep 04 '15 at 08:07
  • 1
    I looked it up and it tinka's solution should work in EF5. Is it maybe a EF7 problem? – Sknecht Sep 04 '15 at 08:28
  • This can happen (in EF6 - don't know about EF7) if the table was originally created with `DatabaseGeneratedOption.None` and you are trying to change it. You could try dropping and recreating the table http://stackoverflow.com/a/18917348/150342 – Colin Sep 04 '15 at 09:34
  • 1
    I already tried to drop the whole DB, deleting the migrations and snapshot file and starting over. Still when I make my DB from code it is not auto incremented. – Sknecht Sep 04 '15 at 09:44

2 Answers2

1

If your table is named admin, AdminId will become an IDENTITY primary key. If that is not the case, you must configure in your DbContext class:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MeineTabelle>(entity =>
        {
            entity.Key(e => e.AdminID);
        });
    }
ErikEJ
  • 40,951
  • 5
  • 75
  • 115
  • 1
    That is how it was in EF6 and before but in EF7 the primary key is not auto increment by default and I don’t know how to activate it other than in my original post. – Sknecht Sep 04 '15 at 12:43
  • @Sknecht is it not working for you, it should work i also found this only solution on internet – wiretext Sep 04 '15 at 12:48
  • 1
    Making AdminID the primary key is not my problem my problem is that it is not auto incremented by default and I don’t get it to work to activate it. – Sknecht Sep 04 '15 at 12:53
  • What version of EF7 do you use? IDENTITY only became default in later beta builds – ErikEJ Sep 04 '15 at 13:13
  • 1
    @ErikEJ I use the 7.0.0-beta5 – Sknecht Sep 04 '15 at 13:17
0

Just drop the ID property from the entity and update database. Again add it back with Database Generated Option. This solution worked fine in my case.

[Table("tblCurrencies")]
public class Currency:DefaultColumns
{
    [DatabaseGenerated( DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Key]
    public string Code { get; set; }

    [Required(AllowEmptyStrings =false), MaxLength(255),Index(IsUnique =true)]
    public string Name { get; set; }

    public string Alies { get; set; }

    public string DecimalName{ get; set; }

    public double CurrenctRate { get; set; }
}
Siraj M
  • 21
  • 2
  • 9