2

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.

Matthew Merryfull
  • 1,466
  • 18
  • 32
  • Are you really trying to do an update or is it an insert? Is your MembershipId field an identity column in your database? – M.Babcock Dec 14 '11 at 01:36
  • Are you updating membership entity as well (changing data in membership table) or changing membership the user relates to (changing FK in user table) or both? – Ladislav Mrnka Dec 14 '11 at 09:57
  • Ladislav Mrnka - I'm updating both the Membership entity and assigning the FK at the same time. The values passed to the membership entity are persisted but the FK is never updated. – Matthew Merryfull Dec 15 '11 at 01:28
  • Did you ever figure this out? I have the exact same problem. – Ray Suelzer Dec 10 '12 at 01:17

0 Answers0