SaveChangesAsync()方法不更新数据库

时间:2018-06-08 14:11:46

标签: c# .net entity-framework entity-framework-6

我的网络应用程序包含:

  • 实体框架 6.1.3
  • Framework .NET 4.5.1

我将.NET Framework从 4.5.1 升级到 4.6.2

因此,“System.Data.Entity”方法的“SaveChangesAsync()”不再更新我的数据库。

我无法找到是因为.NET框架包还是Entity Framework 6.1.3和.NET Framwork 4.6.2之间的“SaveChangesAsync()”方法的一些兼容性问题...我很丢失!< / p>

以下是一些示例:

服务类

public async Task<MyActionResponseModel> UpdateSomething(Catalogue catalogue)
{
    if (catalogue== null) throw new ArgumentNullException("catalogue is null");
    var response = new ActionAddResponse();

    var catalogueToUpdate = await _catalogueRepository.GetCatalogueById(catalogue.Id);
    var myDate = new DateTime();
    if (catalogue.EndDate != null)
    {
        myDate = catalogue.EndDate.Value;
        myDate = myDate.Date.AddHours(23).AddMinutes(59);
    }

    catalogueToUpdate.Year = catalogue.Year;
    catalogueToUpdate.StartDate = catalogue.StartDate;
    catalogueToUpdate.EndDate = catalogue.EndDate!= null ? myDate : catalogue.EndDate;
    catalogueToUpdate.Tax = catalogue.Tax;
    catalogueToUpdate.Online = Convert.ToBoolean(catalogue.Online);
    catalogueToUpdate.RefNote = catalogue.RefNote;

    await _unitOfWork.SaveAsync();

    response.Success = true;
    response.Message = string.Format("Catalogue has been update");

    return response;
}

UnitOfWork类

public class UnitOfWork:IUnitOfWork
{    
    public async Task SaveAsync()
    {
        await _context.SaveChangesAsync(); // System.Data.Entity
    }
}

package.config

<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.6" targetFramework="net451" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.6" targetFramework="net451" />
  <package id="Newtonsoft.Json" version="10.0.1" targetFramework="net451" />
</packages>

我已经检查过我的async / await choregraphy,一切似乎都正确。 那么在那里发生了什么?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我终于找到了我做错的事。 事实上我正在使用“Unity”(版本5.8.6)。我上次在.NET Framework的同时更新了我的Unity包。

我制作了像这样的UnityConfig.c:

public static void ConfigureUnityContainer(IUnityContainer container)
{
    // some other resgistration
    container.RegisterType<MyEntities>(new PerResolveLifetimeManager());
}

错误在于经理的类型。正确的是 PerRequestLifetimeManager

public static void ConfigureUnityContainer(IUnityContainer container)
{
    // some other resgistration
    container.RegisterType<MyEntities>(new PerRequestLifetimeManager());
}

我对 PerRequestLifetimeManager 的理解是,容器将解析http请求中对象的同一个实例,而 PerResolveLifetimeManager 将标记类型,以便在构建对象图中重用实例。

总之,使用 PerRequestLifetimeManager ,在不同的http请求中,我们将使用不同的已解析对象。