0

Attaching an entity of type 'Scheduler.Models.UserImage' 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.

Error Updating an entity with relation 1 to 1:

I have two tables User and UserImage with an relation 0..1. I want to stores pictures of the Users in my application in a different table.

The User Class:

public partial class User
{
    public User()
    {
        this.FirstName = "";
        this.LastName = "";
        this.SurName = "";
        this.Mail = "";
        this.City = "";
        this.IsManager = false;
        this.IsActive = false;
        this.UserLevel = 0;
        this.PhoneNumber = "";
        this.SiteMembers = new ObservableCollection<SiteMember>();
        this.GroupMembers = new ObservableCollection<GroupMember>();
    }

    public int User_ref { get; set; } // PK Autoinc
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string SurName { get; set; }
    public string Mail { get; set; }
    public string City { get; set; }
    public bool IsManager { get; set; }
    public bool IsActive { get; set; }
    public int UserLevel { get; set; }
    public string PhoneNumber { get; set; }
    public string Password { get; set; }

    public virtual ObservableCollection<SiteMember> SiteMembers { get; set; }
    public virtual ObservableCollection<GroupMember> GroupMembers { get; set; }
    public virtual UserImage UserImage { get; set; }
}

The UserImage Class:

public partial class UserImage
{
    public int Image_Ref { get; set; }// Auto Inc
    public int User_Ref { get; set; } //Primary KEy
    public byte[] Image { get; set; }

    public virtual User User { get; set; }
}

I added entities to the recording DbSets.

var entity = new User();
DbSet<User> dbSet = db.Set<User>();
dbSet.Add(entity);
db.Entry(entity).State = EntityState.Added;

var entity = new UserImage();
DbSet<UserImage> dbSet = db.Set<UserImage>();
dbSet.Add(entity);
db.Entry(entity).State = EntityState.Added;

I modify some controls in the form and call save changes in order to generate the primary keys. After the savechanges I have thise code:

var query = db.UserImages.Include(e => e.User);
UserImage usrImg = query.AsNoTracking()
                    .Where(e => e.User_Ref == CurrentEntity.User_ref).FirstOrDefault();
db.Entry(usrImg).Entity.Image = UserImageSelection.Image;
db.Entry(usrImg).State = EntityState.Modified;//Over here crashes

"Attaching an entity of type 'Scheduler.Models.UserImage' 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. "

Where CurrentEntity.User_Ref is actually the User Table.What am I doing wrong here and why cannot modify the UserImage table when in insert mode.

MartinZPetrov
  • 316
  • 5
  • 20
  • Why do you use DbSets to manipulate instances of entities instead of a DbContext? – Luis Jun 24 '16 at 15:53
  • Either way I get the same exception. This only happens when inserting in the two tables at the same time. – MartinZPetrov Jun 24 '16 at 16:04
  • I'm quite sure the AsNoTracking is the source of the problem there (at least I can't see anything else there). Because you tell him to not track the entry, its basically detached from the context logic. so the context still has the entry in its initial state, and now you are adding it from an unmanaged state again, setting its state to modified. When you plan to modify values, you should not use .AsNoTracking(). – DevilSuichiro Jun 24 '16 at 23:15
  • 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

1 Answers1

0

For a 1-1 relationship, I'm fairly sure you need to have the PK of both entities in their respective related entity. For example, person and social security number:

public class Person
{
    public int ID {get;set;}
    public int SocialSecID {get;set;}
}

public class SocialSecurity
{
  public int ID {get;set;}
  public int PersonID {get;set;}
}

Now when you insert in to the tables, both the PK and FK of the entities will need to be unique. But, using this approach you can just query for the SocialSecurity of the person using the SocialSecID property.

Ingenioushax
  • 718
  • 5
  • 20