【问题标题】:Entity Framework: relate identity 2 user to product model实体框架:将身份 2 用户与产品模型相关联
【发布时间】:2015-03-01 21:03:24
【问题描述】:

我正在使用 Web API 2、Entity Framework 6 和 Identity 2

我的产品模型与 ApplicationUser 模型相关,我在其中创建 Product,但出现错误:

附加信息:一个实体对象不能被多个 IEntityChangeTracker 实例引用。

我的模特:

public class Product {
    public int id { get; set; }
    public string url { get; set; }
    public string name {get;set}
    public ApplicationUser user { get; set; }
}

我的创建代码:

public IHttpActionResult PostProduct(Product product) {
    ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));

    product.user = userManager.FindById(User.Identity.GetUserId());

    if (!ModelState.IsValid) {
        return BadRequest(ModelState);
    }

    db.Products.Add(product);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = product.id }, product);
}

【问题讨论】:

  • “db”指的是什么 dbcontext?看起来您有一个上下文带回(并跟踪)用户并将该用户作为属性添加到不同上下文中的对象(也将要跟踪它)
  • 我对两个模型使用一个上下文,我的上下文是 ApplicationDbContext。并且 userManager.FindById(User.Identity.GetUserId()) 不为空
  • product 是否有原始用户 ID 属性?如果是这样,请使用它来建立关联。

标签: entity-framework asp.net-web-api2 asp.net-identity-2


【解决方案1】:

“db”指的是什么 dbcontext?

我猜您可能有多个 dbcontext,并且您正尝试从其中一个检索数据并将其保存在另一个上。

也许您可以更改代码以为每个 http 请求创建一个 dbcontext,并在您的 http post 请求期间重用该上下文。

也许会改变:

ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(new ApplicationDbContext()));

到:

ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));

这将让您保存您的产品,但您应该避免发回 EF 对象,或者至少关闭延迟加载。

为了澄清一点,不要在返回中发回product,因为它包含用于延迟加载的 EF 代理的属性。当您序列化产品对象时,这充其量会导致比您想要返回的数据多得多,而在最坏的情况下 - 您在 cmets 中描述的错误。

【讨论】:

  • 嗨,现在我的错误是:{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent1' type failed to serialize response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"发生错误。","ExceptionMessage":"自引用循环检测到类型为“Khonok.Models.Audio”。路径'user.audios'。","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at ...`
  • 我不建议通过网络序列化和发送实体框架对象,因为您最终可能会发送整个对象图,并且您会收到类似的错误。也许使用 viewmodels / dto
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 2013-12-10
  • 1970-01-01
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多