更新 Entity Framework 4.1 中的外键实体
我目前正在使用 WebApi 构建 REST 服务,并且后备存储使用 EF4.1。我遇到了无法更新外键的问题...
这两个模型类如下所示:
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; }
}
我的应用程序填充了 User 对象和 Membership 对象,并将它们传递给以下 Update 方法:
public User Update(User entity)
{
if(entity.Membership != null)
dbContext.Memberships.Attach(entity.Membership);
dbContext.Entry(entity).State = EntityState.Modified;
dbContext.SaveChanges();
}
我已经确认这两个对象在更新时都存在,但成员资格外键永远不会保留到数据库中。我确信我正在做一些简单的错误。任何见解将不胜感激。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论