1

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);
        }
5
  • Don't pass the identity column property to the Insert, it's telling you why it's a problem in your first error message. The database is setup to not allow custom values in your Identity column, as it appears it auto-increments. Commented Apr 10, 2019 at 18:46
  • Thanks, Without identity Id_mema will AutoNumber? Commented Apr 10, 2019 at 18:49
  • When you place this line IDENTITY(1, 1) it's telling the database to add 1 to the next insert as the id_mema value, you can exclude properties from insertion in entity framework in different ways, please see this article (stackoverflow.com/questions/16340142/…) Commented Apr 10, 2019 at 18:51
  • Why my way is wrong? I read on other forums and it should work Commented Apr 10, 2019 at 19:12
  • Did you read the article I posted in my previous comment? Your model I'm assuming has a property which relates to the identity column in your database table, you need to tell Entity Framework not to use that property when inserting. The article I linked you to has different approaches for excluding a model property from insert. Commented Apr 10, 2019 at 19:14

2 Answers 2

1

If you are c# class to define your entities you might need to do something like this...

   public class Memy
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id_Mema { get; set; }
        public string Autor { get; set; }

Or if you are defining your entity attributes using fluent API you might need to do something like this;

 protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Memy>()
            .Property(p => p.Id_mema)
            .ValueGeneratedOnAdd();
    }

This here should have more information on using the Fluent API and here for more information on decorating your POCOs with attributes to handle the auto-increment.

-HTH

Sign up to request clarification or add additional context in comments.

Comments

0

This error suggests the following: Your Memy table is set to 'Is Identity' = 'True' with auto increment. So you can't insert explict key values, which is logical. Please check in your function, perhaps your method parameter object in CreateMeme has a value for memy.Id_Mema.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateMeme(Memy memy)

Make sure memy.Id_Mema is not assigned by your code explicitly. Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.