1

My application does something strange, if I execute the following code outside the debugger it does not work, but if I run it with the debugger it works fine: keeping in mind that I step through the code, and not continue the next instant.

As I can gather from the debugger, there is nothing wrong with the code, but maybe there is, I at least cannot find it.

public void Reject(string id)
{
    using (context)
    {
        int intId = Convert.ToInt32(id);
        Hours hr = (from h in context.Hours
                    where h.Id == intId
                    select h).FirstOrDefault();
        hr.Status = 30;
        context.SaveChanges();
    }
}

ApplicationDBContext class

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    static ApplicationDbContext()
    {
        System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
    }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }
    public DbSet<Department> Departments { get; set; }
    public DbSet<Tasks> Tasks { get; set; }
    public DbSet<Hours> Hours { get; set; }
    public DbSet<OffDays> OffDays { get; set; }
    public static ApplicationDbContext Create()
    {
            return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>()
            .HasRequired(u => u.Department)
            .WithMany(d => d.Users)
            .Map(c => c.MapKey("DepartmentId"));

        modelBuilder.Entity<ApplicationUser>()
            .HasMany(u => u.Supervisors)
            .WithMany();

        modelBuilder.Entity<Department>()
            .HasMany(d => d.Supervisors)
            .WithOptional()
            .Map(c => c.MapKey("SupervisorId"));

        modelBuilder.Entity<Hours>()
            .HasRequired(u => u.UserId)
            .WithMany(h => h.Hours)
            .Map((c => c.MapKey("Hours")));
    }
}

Do you guys have an idea what I can try?

19
  • 1
    Do you get an exception? Is context an instance field? Do you set it via the constructor? Do you call Reject or other methods multiple times for the same instance of the containing class? Commented May 13, 2016 at 12:06
  • Make sure you are looking at the correct database. Are you using a file-based database, ie use AttachDBFileName in the connection string? Commented May 13, 2016 at 12:06
  • I am using a file based database, the context is set in my baseController (it is MVC), and used everywhere, it connects to the right DB and I do not get an exception. CustomController>BaseController>Controller, that is the extention on my controllers Commented May 13, 2016 at 12:08
  • 2
    No, you aren't. The "correct" database is the file copied inside your bin/debug folder which always gets overwrittend when you hit F5. Why are you using a file-based database anyway? They don't scale, they are deprecated and they will be removed in a future versions. Check Aaron Bertrand's article on why you shouldn't use them Commented May 13, 2016 at 12:19
  • @PanagiotisKanavos connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-something.mdf;Initial Catalog=aspnet-aspnet-something; That is how I declaired it, I assume that is the correct connectionstring. Commented May 13, 2016 at 12:23

2 Answers 2

1

It looks like you are reusing the same DbContext instance through the life of your application. This goes against Microsoft's recommended best practices, and may introduce some of the odd behavior you are seeing. DbContext manages a LOT of cached data inside each DbContext instance, and keeping it alive for the entire application can cause all sort of craziness as different cached entities are returned. This caching is what I think is causing your problem. Somewhere in your application this instance is getting disconnected from the context, and now that disconnected, cached instance is being returned the next time you ask for it.

The current Entity Framework best practices recommend that you create a new instance of the context for each logical "unit of work".

The easiest way to create a new context instance on demand is like this:

using (var context = new ApplicationDbContext())
{
    //Code here that uses the context
}
Sign up to request clarification or add additional context in comments.

Comments

0

You must first attach the entity that you have retrieved

public void Reject(string id)
{
    using (context)
    {
        int intId = Convert.ToInt32(id);
        Hours hr = (from h in context.Hours
                where h.Id == intId
                select h).FirstOrDefault();
        context.Attach( hr);// here is difference
        hr.Status = 30;
        context.SaveChanges();
   }
}

12 Comments

The entity should already be attached by default unless he did something strange to the way the context is configured.
There is no reason to reattach an entity that was just loaded unless change tracking has been disabled explicitly
You are a magician, It works, first try, every try! @BradleyUffner my context works as supposed on every other page I made, so maybe it was a fluke that it worked on that pages, but at least I know the fix and will "fix" it on my other pages!
If you use context = new context(); entity will be attached by default . May be your instance of context will change in your code .if my answer doesn't work comment to me .I will delete it
@FalingDutchman no it didn't work and SHOULD NOT be used by others. You still don't know what the problem is. You just glossed over it. Why was the entity detached? Why isn't this problem reproducible? How are you certain that some other method won't break if you don't know what to fix? Something is wrong with the context and this problem will appear again
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.