Updating foreign key entities in Entity Framework 4.1

泄露秘密 提交于 2019-12-06 12:07:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!