0

I am stuck on a small problem. I want to remove one row based on an ID. But I keep deleting all my rows instead.

This is my code in my datalayer. You can read the word "eigenaar" as "owner".

public void removeEigenaar(int eigenaarID)
    {
        transaction = connection.BeginTransaction();
        try
        {
            using (context = new MyDbContext(connection, false))
            {
                context.Database.Log = (string message) => { Console.WriteLine(message); };
                context.Database.UseTransaction(transaction);
                //----------------------------

                Eigenaar e =
                    (from s in context.Eigenaars
                     where s.ID == eigenaarID
                     select s).First();
                context.Eigenaars.Remove(e);

                //----------------------------
                context.SaveChanges();
            }
            transaction.Commit();
        }
        catch
        {
            transaction.Rollback();
            throw;
        }
    }

If I debug the code, i can see that my "e" is filled with one owner. That's what i find so strange.

edit sql

My delete query works, it just deletes way to much.

ToonDoe
  • 11
  • 5

3 Answers3

0

Try adding:

context.Entry(e).State = EntityState.Modified;

before

context.SaveChanges();
Sushrut Kanetkar
  • 363
  • 3
  • 13
0

Found the problem.

In my mydbcontext.cs i added:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Eigenaar>().MapToStoredProcedures();
        modelBuilder.Entity<Eigendom>().MapToStoredProcedures();
        modelBuilder.Entity<Eigenschap>().MapToStoredProcedures();
        modelBuilder.Entity<Overeenkomst>().MapToStoredProcedures();
        modelBuilder.Entity<Panden_has_eigenschappen>().MapToStoredProcedures();
    }

Removing this code fixed it.

ToonDoe
  • 11
  • 5
0

Some Modification of your code:

IEnumerable<Eigenaar> e= (from s in context.Eigenaars
                 where s.ID == eigenaarID
                 select s).ToList();    
context.Eigenaars.DeleteAllOnSubmit(e);
context.SubmitChanges();

OR

You could do a normal SQL truncate or delete command, using the DataContext.ExecuteCommand method:

context.ExecuteCommand("DELETE FROM Entity");

Or

context.ExecuteCommand("TRUNCATE TABLE Entity");
Vikash sah
  • 92
  • 4