mvc4 key error An item with the same key has already been added

An item with the same key has already been added.

Thats the error im getting when i'll try to submit, i know it is been cuz i have two rows with the same name in workhoursmodel, but how can i fix it - is there any easy way to fix or do i have to breakdown the table and recreate it?

ps im really new to mvc so a bit of help would be nice ds

My controller

   public ActionResult Create()
    {
        WorkhoursModels model = new WorkhoursModels();
        model.Workstations = db.WorkStation.AsEnumerable().Select(x => new SelectListItem() { Text = x.WorkStations, Value = x.Id.ToString() });
        return View(model);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(WorkhoursModels workhoursmodels)
    {
        db.WorkHours.Add(workhoursmodels);
        db.SaveChanges();
        return View();
    }

{

My model

{
    [Table("WorkHoursModels")]
    public class WorkhoursModels
    {
        public int Id { get; set; }
        public string Start { get; set; }
        public string Stop { get; set; }
        public string command { get; set; }
        public string Users { get; set; }
        public IEnumerable<System.Web.Mvc.SelectListItem> Workstations { get; set; }
        public string WorkStations { set; get; }
    }
        [Table("WorkStations")]
        public class WorkHoursStation
        {
            public int Id { get; set; }
            public string WorkStations { get; set; }
            public IEnumerable<SelectListItem> Workstation { get; set; }
        }



        public class WorkhourDB : DbContext 
        {
            public DbSet<WorkhoursModels> WorkHours { get; set; }
            public DbSet<WorkHoursStation> WorkStation { get; set; }
        }
    }

my view

 @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div class="editor-label">
            @Html.LabelFor(model => model.Users)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.Users)
            @Html.ValidationMessageFor(model => model.Users)
        </div>

     <div class="editor-field">
     @Html.DropDownListFor(model => model.Id, Model.Workstations, string.Empty)
    </div>
    <p>
        <input type="submit"  value="Create" />
    </p>

 }

Updated the question with database information

CREATE TABLE [dbo].[WorkhoursModels] (
    [Id]           INT            IDENTITY (1, 1) NOT NULL,
    [Start]        NVARCHAR (50) NULL,
    [Stop]         NVARCHAR (50) NULL,
    [command]      NVARCHAR (50) NULL,
    [users]        NVARCHAR (MAX) NULL,
    [WorkStations] NVARCHAR (50) NULL,
    CONSTRAINT [PK_dbo.WorkhoursModels] PRIMARY KEY NONCLUSTERED ([Id] ASC)
);

Upvotes: 0

Views: 4538

Answers (3)

I managed to find a solution creating.

I added this to my workhoursmodel

 public virtual WorkStation WorkStation { get; set; } 

and then i added this to my workstation model

public virtual ICollection<Workhourmodels> Workhourmodels{ get; set; }

then i fixed my selectlist

    ViewBag.WorkStation = new SelectList(db.WorkStation, "Id", "WorkStation");
    return View();

Upvotes: 1

Ruoyu Jiang
Ruoyu Jiang

Reputation: 195

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(WorkhoursModels workhoursmodels)//object workhoursmodels object has some connection with 
{
    db.WorkHours.Add(workhoursmodels);
    db.SaveChanges();
    return View();
}
//try to create a new object workhoursmodel and get all information you need from the object post from view
//eg:
WorkHours workHours = new WorkHours();
workHours.Users = workhoursmodels.Users

Upvotes: 0

Mike Beeler
Mike Beeler

Reputation: 4101

You have an already existing key in the database, if the key looks ok in the database update if the record exists otherwise add. See example

Handle both the add and update cases

Handle both the add and update cases

public void Persist(Company company)
{
  var companyInDb = _dbSet.SingleOrDefault(c => c.Id == company.Id);
  if (companyInDb != null)
  {
     _context.Entry(companyInDb).CurrentValues.SetValues(company);
  }
  else
  {
    _dbSet.Add(company);
  }
    _context.SaveChanges();
}

Upvotes: 0

Related Questions