Why this code doesn't work? I want insert into database record with currently logged in user's UserName.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateMeme(Memy memy)
{
var user=await GetCurrentUser();
memy.Autor = user.UserName;
memy.Like = 0;
memy.Dislike = 0;
if (ModelState.IsValid)
{
_context.Memy.Add(memy);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(memy);
}
This is table:
CREATE TABLE [dbo].[Memy] (
[Id_mema] INT IDENTITY (1, 1) NOT NULL,
[autor] TEXT NULL,
[like] INT NULL,
[dislike] INT NULL,
PRIMARY KEY CLUSTERED ([Id_mema] ASC)
);
I have 2 errors: " Cannot insert explicit value for identity column in table 'Memy' when IDENTITY_INSERT is set to OFF"
And
"An error occurred while updating the entries. See the inner exception for details"
How to resolve this?
EDIT
Method CreateMeme
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateMeme(Memy memy)
{
var user=await GetCurrentUser();
memy.Autor = user.UserName;
memy.Like = 0;
memy.Dislike = 0;
if (ModelState.IsValid)
{
_context.Memy.Add(memy);
_context.SaveChanges();
return RedirectToAction("Index", "Home", new { area = "" });
}
return View(memy);
}
IDENTITY(1, 1)it's telling the database to add 1 to the next insert as theid_memavalue, you can exclude properties from insertion in entity framework in different ways, please see this article (stackoverflow.com/questions/16340142/…)