我正在尝试通过将我的 DbContext 注入服务类来在我的 ASP.NET Web 窗体项目中实现现代实践(使用服务、IoC 等),但我一直收到一条错误消息An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
这让我很困惑,因为我相对确定我只有一个 DbContext 跟踪更改。
有什么问题?我正在使用将 DbContext 作为函数参数发送到的静态类,但除此之外,我没有在页面端进行任何更改...
public partial class Create : System.Web.UI.Page
{
private LicenseService licenseService;
private ApplicationDbContext context = new ApplicationDbContext();
protected void Page_Load(object sender, EventArgs e)
{
try
{
licenseService = new LicenseService(context);
}
catch (Exception ex)
{
// TODO Add error handling/logging.
ErrorMessage.Text = ex.Message;
}
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
this.context.Dispose();
}
protected async void Save_Click(object sender, EventArgs e)
{
try
{
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
await SaveLicenseAsync(user);
// Show a message that the work was done.
ShowSnackbar("License was successfully added; redirecting...", "Default");
}
catch (Exception ex)
{
// TODO Add error handling/logging.
ErrorMessage.Text = ex.Message;
}
}
private async Task SaveLicenseAsync(ApplicationUser user)
{
// Get the specified expiry date.
DateTime.TryParse(ExpiryDatePicker.SelectedDate.ToString(), out DateTime expiryDate);
// Create the viewmodel that will be passed to the service.
var model = new LicenseViewModel
{
ExpiryDate = expiryDate,
Name = NameTextBox.Text
};
await licenseService.AddAsync(model, user);
}
}
我的服务通常包含与 EF 的所有交互。我喜欢这个,因为它将页面与 DbContext 逻辑分开。
潇潇雨雨
相关分类