0

I have a table that I am trying to update. Here is my model.

public class Preference
{
    [Key, ForeignKey("Profile"), Column(Order = 0)]
    public int UserId { get; set; }
    public virtual Profile Profile { get; set; }

    [Key, ForeignKey("PrefAvatar"), Column(Order = 1)]
    public int AvatarId { get; set; }
    public virtual PrefAvatar PrefAvatar { get; set; }

    [Key, ForeignKey("PrefSidebar"), Column(Order = 2)]
    public int SidebarId { get; set; }
    public virtual PrefSidebar PrefSidebar { get; set; }
}

In the Edit GET method, in order for me to get the right set of preferences for the user logged in, I am get the user Identity and match it up to the autoId ID in the users table and set it to id, then get the single record that contains that user's preferences, like so:

var id = result.UserId;
var Preferences = db.Preferences.SingleOrDefault(a => a.UserId == id);

This allows the user to see his current preferences. My trouble comes when I try to save. Trying to implement the suggestions provided here on stackoverflow as well as the one here on microsoftdocs, I get a The property 'AvatarId' is part of the object's key information and cannot be modified when I try to update the record.This is what I have tried:

public ActionResult Edit(Preference preference)
{
    var user = User.Identity.Name;
    var userId = (from ui in db.Profiles where user == ui.someUser select ui.Id).SingleOrDefault();
    var result = (from r in db.Preferences where userId == r.UserId select r).SingleOrDefault();
    var id = result.UserId;
    var myPreferences = db.Preferences.SingleOrDefault(am => am.UserId == id);
    if (TryUpdateModel(myPreferences))
    {
        db.SaveChanges();
        return View(preference);
    }
    return View(preference);
}
Skullomania
  • 2,225
  • 2
  • 29
  • 65
  • 3
    Key columns can't be updated. Delete the row and make a new one. Or don't make these columns primary keys of this table. If you have a need to update one of these objects, it's a good sign they shouldn't be keys. –  Nov 20 '17 at 17:50
  • @Amy, Please make your suggestion a solution – Skullomania Nov 20 '17 at 18:28

1 Answers1

0

You can try adding a key specifically for Preference, and then make the foreign keys just foreign keys, and not keys

[Key]
public int PreferenceId { get; set; }

[ForeignKey("Profile"), Column(Order = 0)]
public int UserId { get; set; }
public virtual Profile Profile { get; set; }

...
  • I tried this, Entity said that Identity_Insert was Off. I did not try the edit that you have. I will test this and post back – Skullomania Nov 20 '17 at 17:53