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

Well, I have the following model structure: I have one class - DatabaseEntitywhich is basically

public class DatabaseEntity
{
    public int Id { get; set; }
}

therefore, every object, such as a product, category, etc., inherits DatabaseEntityand has a property Id. I also have a typical repository class EntityFrameworkwith a method InsertOrUpdate:

private readonly DbContext _database;

public void InsertOrUpdate<TObject>(TObject entity) where TObject : DatabaseEntity
{
    if(entity.Id == default(int))
    {
         // New entity
         DbSet<TObject>().Add(entity);
    }
    else
    {
         // Existing entity
         _database.Entry(entity).State = EntityState.Modified;
    }
    _database.SaveChanges();
}

Then I boot from eBay through the list of eBay api categories that I have to add to the database. Mainly category:

public class EbayCategory : DatabaseEntity
{
    // It has Id since it inherits DatabaseEntity
    public string Name { get; set; }      
    // ... some other properties
}

But the problem is that when I load the categories that I load, and their identifier properties, which, of course, already have values. And when I try to save them in a database, for example:

public void UpdateCategories(IEnumerable<EbayCategory> newCategories)
{
    foreach (var newCategory in newCategories)
    {
        _repository.InsertOrUpdate(newCategory);
    }
}

... , entity.Id != default(int), , , , :

System.Data.Entity.Infrastructure.DbUpdateConcurencyException
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."

... , - , . InsertOrUpdate, (EbayCategories) (Id) , / , EbayCategory.Id ?

+4
2

, , , , , , DatabaseEntity

public class EbayCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID
    {
        get { return base.ID; }
        set { base.ID = value; }
    }

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

InsertOrUpdate , :

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();
}
+8

, , . , .

: . EntityTypeConfiguration:

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

modelBuilder : fooobar.com/questions/185106/...

+3

Source: https://habr.com/ru/post/1536052/


All Articles