Go this one tonight, and caused me some grief for a bit.
Basically, I have a foreign key mapping to my company into my user profile and I was trying to perform an update on the foreign key. Here's my user profile:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public string Firstname { get; set; }
public string Surname { get; set; }
[ForeignKey("CompanyId")]
public Company Company { get; set; }
public int CompanyId { get; set; }
}
if you want to update the company you have to set the company to null but set the foreign key seperately :
using (var context = new UsersContext())
{
profile.UserName = userViewModel.UserName;
profile.EmailAddress = userViewModel.EmailAddress;
profile.Firstname = userViewModel.FirstName;
profile.Surname = userViewModel.Surname;
profile.Company = null;
profile.CompanyId = userViewModel.CompanyId;
//profile.Company = userViewModel.Companies.FirstOrDefault(c => c.Id == userViewModel.CompanyId);
context.Entry(profile).State = EntityState.Modified;
context.SaveChanges();
}
now it works !
No comments:
Post a Comment