Fix exception with Entity-Framework?

Hi,

I am using EntityFramework for my ASP.NET MVC website, but have some upgrade issues.

This is what my update code looks like:

using (BissEntities context = new BissEntities())
    {

      if (adCategoryFilter.Id < 1)
        context.AddToAdCategoryFilter(adCategoryFilter);
      else
        context.Refresh(System.Data.Objects.RefreshMode.ClientWins, adCategoryFilter);

      if (context.SaveChanges() > 0)
        return true;
    }
    return false;

When I execute context.Refresh, I get the following exception:

An item with index 0 in the collection of objects to update is null EntityKey or not attached to this ObjectStateManager.

Stacktrace :    at System.Data.Objects.ObjectContext.RefreshCheck(Dictionary`2 entities, Object entity, EntityKey key)
   at System.Data.Objects.ObjectContext.AddRefreshKey(Object entityLike, Dictionary`2 entities, Dictionary`2 currentKeys)
   at System.Data.Objects.ObjectContext.RefreshEntities(RefreshMode refreshMode, IEnumerable collection)
   at System.Data.Objects.ObjectContext.Refresh(RefreshMode refreshMode, Object entity)
   at Biss.Models.FilterModel.UpdateCategoryFilter(AdCategoryFilter adCategoryFilter) in C:\Users\Snowman\Documents\Visual Studio 2010\Projects\Biss\Biss\Models\FilterModel.cs:line 86 

This is not the first time I get this problem. At first I thought that this might be related to relationships in the database, but after they were deleted from the processed table, the same exception remained.

Where did the adCategoryFilter attribute come from?

adCategoryFilter (), ViewObject ( -). , ( db).

, .

BestRegards

+3
2

ASP.NET MVC, . , , , " Entity" "".

, EF, .

:

using (BissEntities context = new BissEntities())
{
  if (adCategoryFilter.Id < 1)
    context.AdCategoryFilters.AddObject(adCategoryFilter);
  else {
     var stub = new AdCategoryFilters { Id = adCategoryFilter.Id };
     context.AdCategoryFilters.Attach(stub);
     context.AdCategoryFilters.ApplyCurrentValues(adCategoryFilter);
  }

  context.SaveChanges();
}

.

, , , ( - "Id" ).

"" ( EF), UPDATE, .

UpdateModel, POCO, .. - "UpdateModel" / - ( ) .

"if Id < 1, a add" ASP.NET MVC - , 0, , , .

- /.

.

+5

, , - auto-mapper ( UpdateModel MVC)

EntityKey - id, . , .

( #, , , ):

var context = new MyEntities();
var originalObject = context.MyObjectSet.Single(x => x.Id == viewmodel.Id);
UpdateModel(originalObject);
context.SaveChanges();

, EntityKey. id / , EntityKey , .

+4

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


All Articles