Home > Mobile >  SaveChanges() does not work anywhere in the whole project. (Entity Framework)
SaveChanges() does not work anywhere in the whole project. (Entity Framework)

Time:05-24

I am currently working on a project, where the company wants me to migrate the whole project from Telerik to EF.

The old project used a lot of automatically generated code from Telerik, but now I can't use it anymore. So I decided to generate it using EF, so I used it, and I generated the whole EntitiesModel: This is what I generated

But I found out that SaveChanges() suddenly has stopped working: Small part of the program

It have no definition.

I am getting this error message: 'EntitiesModel' does not contain a definition for 'SaveChanges', and no accessible extension method 'SaveChanges' accepting a first argument of type 'EntitiesModel' could be found (are you missing a using directive or an assembly reference?)

I don't know how to fix this issue. Could you help me out, please?

EDIT: I found out that the last fellow who was writing this code done this, I need to repair it. Would you recommend me please how should I do it? Quickfixcode...

CodePudding user response:

SaveChanges() is an Entity Framework DbContext method. As far as I know, it does not exist on the type you're trying to use it on.

https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.dbcontext.savechanges?view=entity-framework-6.2.0

Supposing you've set up your project and entity framework correctly, if you want to delete any entry in your DB using EF, you'll first have to instanciate or inject AkroEntities DbContext and do something like the following :

var entity = akroEntitiesInstance.TFirmyLokalitas.FirstOrDefault(f => f.id == primaryKey)

if (entity != null)
{
    akroEntitiesInstance.TFirmyLokalitas.Delete(entity);
    akroEntitiesInstance.SaveChanges();
}

CodePudding user response:

To access the context or Entity of the project, you need to define it in the constructor and be able to access the desired tables.

Test the following code:

  private readonly AcroEntities _akroEntitiesInstance;
  public YourController(AcroEntities  akroEntitiesInstance)
  {
      _akroEntitiesInstance= akroEntitiesInstance;
  }

  public static void Delete(int key)
  {
   var Item = _akroEntitiesInstance.TFirmyLokalitas.FirstOrDefault(f => 
   f.id == key);

     if(Item != null)
     {
        _akroEntitiesInstance.TFirmyLokalitas.Delete(Item);
        _akroEntitiesInstance.SaveChanges();
     }
  }
  • Related