1

I have a model like:

public class Sample
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid SampleId { get; set; }

    public virtual SampleProperty Saloon { get; set; }
    public virtual SampleProperty Room { get; set; }
    public virtual SampleProperty Balcony { get; set; }
}

and a related entity:

public class SampleProperty
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public Piece Piece { get; set; }
    public FloorType Floor { get; set; }
    public WallType Wall { get; set; }
    public DoorType Door { get; set; }
    public WindowType Window { get; set; }
}

and ofcourse related Enums for the types in SampleProperty Entity.

Related controller is:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Sample(Sample model)
    {
        if (ModelState.IsValid)
        {
            db.Entry(model.Saloon).State = EntityState.Modified;
            db.Entry(model.Room).State = EntityState.Modified;
            db.Entry(model.Balcony).State = EntityState.Modified;
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }

Controller during get operation is:

    [HttpGet]
    public ActionResult Sample(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Sample @sample = db.Samples.Where(x => x.SampleId == id).FirstOrDefault();
        if (@sample == null)
        {
            return HttpNotFound();
        }
        @sample.Room = new SampleProperties();
        @sample.Saloon = new SampleProperties();
        @sample.Balcony = new SampleProperties();

        return View(@sample);
    }

By the way; I am including following properties in View;

                        @Html.HiddenFor(model => model.Saloon.Id)
                        @Html.HiddenFor(model => model.Room.Id)
                        @Html.HiddenFor(model => model.Balcony.Id)

My problem is: When I try to update this entity. I am having error below. Do you have any idea?

Attaching an entity of type 'Project.Models.SampleProperties' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Görkem Öğüt
  • 1,761
  • 3
  • 18
  • 29
  • Do you in any way prevent that two (or three) of the `SampleProperty` references are set to the same object? If not, that would be a source of possible exceptions because you can attach the same key twice. Anyhow, I think you better convert this into a 1:n association. – Gert Arnold Jan 01 '14 at 21:26
  • I didn't want to create separate objects having same attributes. But of course that can be an option if can't find a solution. Thank you! – Görkem Öğüt Jan 01 '14 at 21:47
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:28
  • You might have a look at my answer on [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent/39557606#39557606). – Murat Yıldız Sep 18 '16 at 12:29

3 Answers3

1

In my case this exception was fired because I was Attaching the same Entity (class) with the same Pk twice. E.g.:

db.Users.Attach(dbRecord.CreatorUser);
db.Users.Attach(dbRecord.OwnerUser); //<- If CreatorUser== OwnerUser then ERROR

You can avoid this using a simple comparison:

db.Users.Attach(dbRecord.CreatorUser);
if (dbRecord.CreatorUser.Pk != dbRecord.OwnerUser.Pk)
{
    db.Cabinets.Attach(dbRecord.OwnerUser);
}
0

Attaching an entity of type 'Project.Models.SampleProperties' failed because another entity of the same type already has the same primary key value.` it appears you are attaching an entity.

You haven't displayed the code that is attaching the entity (which would be helpful). However, most likely the entity is already attached/materialized from the database to the context somehow. So what you are looking for is a the most reasonable way to find out if an entity is attached to the dbcontext.

There is also the chance that you haven't attached (DbSet.Attach) the model back to the DbContext.

Update

I think your code should look like:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Sample(Sample model)
    {
        if (ModelState.IsValid)
        {
            // Added Line
            db.Samples.Attach(model);

            db.Entry(model.Saloon).State = EntityState.Modified;
            db.Entry(model.Room).State = EntityState.Modified;
            db.Entry(model.Balcony).State = EntityState.Modified;
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(model);
    }
Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

Actually, it is not the answer for my question but I couldn't find a proper solution rather than assigning all the entities as seperate objects in the same entity like:

public class Sample
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid SampleId { get; set; }

    public Piece SaloonPiece { get; set; }
    public FloorType SaloonFloor { get; set; }
    public WallType SaloonWall { get; set; }
    public DoorType SaloonDoor { get; set; }
    public WindowType SaloonWindow { get; set; }
    public Piece RoomPiece { get; set; }
    public FloorType RoomFloor { get; set; }
    public WallType RoomWall { get; set; }
    public DoorType RoomDoor { get; set; }
    public WindowType RoomWindow { get; set; }
    public Piece BalconyPiece { get; set; }
    public FloorType BalconyFloor { get; set; }
    public WallType BalconyWall { get; set; }
    public DoorType BalconyDoor { get; set; }
    public WindowType BalconyWindow { get; set; }
}

I know, it is not charming...

Görkem Öğüt
  • 1,761
  • 3
  • 18
  • 29