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