Custom Autohistory
I have updated my project to .Net core 3.0.
Following the article, I did the below in my MVC web application project
class CustomAutoHistory : AutoHistory
{
public int UserId { get; set; }
}
Then register it in the db context like follows:
modelBuilder.EnableAutoHistory<CustomAutoHistory>(o => { });
Then in my MVC controller code I did below
if (ModelState.IsValid)
{
try
{
_context.EnsureAutoHistory(() => new CustomAutoHistory()
{
UserId = Convert.ToInt16( User.FindFirstValue(ClaimTypes.NameIdentifier))
});
_context.Update(cust);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClientExists(cust.Id))
{
return NotFound();
}
else
{
throw;
}
}
}
CustomAutoHistory table script
CREATE TABLE [dbo].[|CustomAutoHistory]( [Id] [int] IDENTITY(1,1) NOT NULL, [RowId] nvarchar NOT NULL, [TableName] nvarchar NOT NULL, [Changed] nvarchar NULL, [Kind] [int] NOT NULL, [Created] datetime2 NOT NULL, [UserId] [int] NULL, CONSTRAINT [PK_CustomAutoHistory] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
GO
The customer records gets updated but there is no record in the Custom History table. Can you please check the custom AutoHistory?
Change the order of operations like so:
if (ModelState.IsValid)
{
try
{
_context.Update(cust);
_context.EnsureAutoHistory(() => new CustomAutoHistory()
{
UserId = Convert.ToInt16(User.FindFirstValue(ClaimTypes.NameIdentifier))
});
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClientExists(cust.Id))
{
return NotFound();
}
else
{
throw;
}
}
}
and try again