How to manually set entity primary key in Entity Framework code first database?

被刻印的时光 ゝ 提交于 2019-12-05 07:48:09

To allow you to manually generate Ids you need a class that has a manually generated ID - so it cannot inherit from DatabaseEntity

public class EbayCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public string Name { get; set; }      
    // ... some other properties
}

Now you will need a different InsertOrUpdate to handle entities that have manually generated keys:

public void InsertOrUpdate(EbayCategory entity)
{
    if(Find(entity.ID == null)
    {
         // New entity
         DbSet<EbayCategory>().Add(entity);
    }
    else
    {
         // Existing entity
         _database.Entry(entity).State = EntityState.Modified;
    }
    _database.SaveChanges();
}
brendanrichards

Colin's answer above quite correctly shows how to achieve this setting using data annotations. But in the presented problem the entity is a subclass so you can't add the annotation without changing the entity class.

There is an alternative configuration method: Fluent Configuration. Here's my example using an EntityTypeConfiguration class:

public class LookupSchoolsConfiguration : EntityTypeConfiguration<LookupSchools>
    {
        public LookupSchoolsConfiguration()
        {
            Property(l => l.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }
    }

You can also add configuration directly to the modelBuilder as per this post: https://stackoverflow.com/a/4999894/486028

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