实体框架表不更新数据库

时间:2016-05-13 12:04:12

标签: entity-framework

我的应用程序做了一些奇怪的事情,如果我在调试器外面执行以下代码它不起作用,但如果我用调试器运行它可以正常工作:请记住我单步执行代码,而不是继续下一个瞬间。

正如我可以从调试器中收集的那样,代码没有任何问题,但也许有,我至少找不到它。

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类

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

你们知道我能尝试什么吗?

2 个答案:

答案 0 :(得分:1)

看起来您在应用程序的生命周期中重复使用相同的DbContext实例。这违反了Microsoft推荐的最佳做法,可能会引入您所看到的一些奇怪行为。 DbContext在每个DbContext实例中管理大量缓存数据,并为整个应用程序保持活动状态可能会导致各种疯狂,因为返回了不同的缓存实体。这个缓存是我认为导致你的问题。在您的应用程序的某个地方,此实例与上下文断开连接,现在,在您下次请求时,将返回已断开连接的缓存实例。

当前的实体框架最佳实践建议您为每个逻辑&#34;工作单元创建一个新的上下文实例&#34;。

按需创建新上下文实例的最简单方法是:

using (var context = new ApplicationDbContext())
{
    //Code here that uses the context
}

答案 1 :(得分:0)

您必须先附加已检索的实体

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();
   }
}
相关问题