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

c# entity-framework primary-key

Question

I have the model structure listed below. I just take one class.DatabaseEntity which, in essence

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

Each entity, such as a product or category, will inherit.DatabaseEntity with haveId property. I also have the usualEntityFramework class repository withInsertOrUpdate method:

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

The categories I need to add to my database are then downloaded from eBay via the eBay api. In essence, category is:

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

The issue is that those categories and their Id attributes, which naturally already contain values, are downloaded along with them. In addition, when I attempt to store them to a database,

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

I have some problems. To start with,entity.Id != default(int) Repository attempts to update this object rather of adding it because it contains value, but since it is not in the database or context, it throws the following exception:

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."

Because it believes that the entity I am trying to update was deleted by someone else. Given that many projects rely on this InsertOrUpdate logic and that I'd like to be able to add items (EbayCategories using the main key (Id ) to a database, edit or delete them like other entities without throwing them away.EbayCategory.Id value?

1
6
4/11/2014 7:55:47 AM

Popular Answer

ZZZ_tmp
10
7/26/2018 10:31:03 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow