简体   繁体   中英

Insert values into database- Entity Framework

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);
        }

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM