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

梦想与她 提交于 2020-01-02 01:03:53

问题


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


来源:https://stackoverflow.com/questions/5820354/entity-framework-4-1-code-first-keyattribute-as-non-identity-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!