问题
I'm currently building a REST service using WebApi and the backing store is using EF4.1. I've run into a snag whereby I cannot update the foreign key...
The 2 model classes look like:
public class User
{
[Key]
public int UserId { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
//
// Membership
public Membership Membership { get; set; }
}
public class Membership: Base
{
[Key]
public int MembershipId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public virtual Collection<User> Users { get; set; }
}
My application populates both the User object and the Membership object and passes them both to the following Update method:
public User Update(User entity)
{
if(entity.Membership != null)
dbContext.Memberships.Attach(entity.Membership);
dbContext.Entry(entity).State = EntityState.Modified;
dbContext.SaveChanges();
}
I've confirmed that both objects are present at the point of updating, but the membership foreign key is never persisted to the database. I'm certain I'm doing something simple wrong. Any insight would be greatly appreciated.
Thanks.
来源:https://stackoverflow.com/questions/8498501/updating-foreign-key-entities-in-entity-framework-4-1