Entity Framework 4.1 code-first KeyAttribute as no

2019-04-19 12:01发布

问题:

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

回答1:

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.



回答2:

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


回答3:

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