Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4.1 code-first KeyAttribute as non-identity column

I've got a problem with a code-first model I've got. Data is now in the database so I can't re-seed the database using a DropCreateDatabaseIfModelChanges class, but I need to change one table so that a bigint column is not an IDENTITY(1,1). I've managed to do this using SSMS but now my EF code is saying it's out of date. This is the code for the table in question:

public class Vote {
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public long FacebookUserId { get; set; }
    [Required]
    public Entity Entity { get; set; }
}

So I've changed my table schema, and my model (which I thought was the reflection of it, but I'm obviously wrong), but EF is still saying my model is out of date, and I can't re-seed the database to get it "perfect".

Any help would be much appreciated.

Thanks,

Benjamin

like image 875
Jamie Howarth Avatar asked Apr 28 '11 14:04

Jamie Howarth


3 Answers

Using data annotation:

public class Customer
{
[Key]

    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CustomerID { get; set; }
}

Using fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>().Property(c => c.CustomerID).HasDatabaseGeneratedOption(null);
    base.OnModelCreating(modelBuilder);
}
like image 147
Shehab Fawzy Avatar answered Nov 10 '22 22:11

Shehab Fawzy


referring to this post ...

It seems that entity framework expects by default that you insert into identity column.

to solve this try

    modelBuilder.Entity<BOB>()
    .HasKey(p => p.Id)
        .Property(p => p.Id)
            .StoreGeneratedPattern = StoreGeneratedPattern.None;

builder.Entity<BOB>().MapSingleType().ToTable("BOB");

or decorate your key in the POCO with ...

 [Key]
 [DatabaseGenerated(DatabaseGeneratedOption.None)]
 public Int64 PolicyID { get; set; }
like image 4
Ahmed Eid Yamany Avatar answered Nov 10 '22 21:11

Ahmed Eid Yamany


Try add this to your OnModelCreating:

modelBuilder.Conventions.Remove<IncludeMetadataConvention>();

That should remove the exception that model is out of date but till this time you must always synchronize model and database manually.

like image 2
Ladislav Mrnka Avatar answered Nov 10 '22 20:11

Ladislav Mrnka