我将使用Entity Framework和ASP.NET MVC应用程序将博客插入我的数据库。如果我要将实体添加到上下文中,我在下面的代码的最后一行出现了这个错误。
InvalidOperationException
:多个IEntityChangeTracker
实例无法引用实体对象。
这是我的代码:
public class AdminController : Controller
{
[HttpPost]
public ActionResult CreateBlog(BlogViewModel vm)
{
try
{
_blogService.Insert(new Blog()
{
Titel = vm.Titel,
Beschrijving = vm.Beschrijving,
Content = (vm.Actie.ToLower() == "publiceer" ? true : false),
Verwijderd = false,
Auteur = UserManager.FindById(User.Identity.GetUserId())
});
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return RedirectToAction(nameof(Blog));
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public AdminController(ApplicationUserManager userManager, IBlogService blog)
{
UserManager = userManager;
_blogService = blog;
}
}
public class BlogService : IBlogService
{
public void Insert(Blog blog)
{
_blogRepo.Insert(blog);
_blogRepo.SaveChanges();
}
}
public class BlogRepo : GenericRepo<Blog>
{
public override Blog Insert(Blog blog)
{
context.Entry(blog.Auteur).State = EntityState.Unchanged;
return dbSet.Add(blog); // --> on this line
}
}
你能找到我制作的问题吗?提前谢谢。
答案 0 :(得分:2)
我认为您的实体模型如下:
public class Blog
{
[Key]
public int Id { get; set; }
[Required]
// etc
public string Titel { get; set; }
public string Beschrijving { get; set; }
public bool Content { get; set; }
public bool Verwijderd { get; set; }
public ApplicationUser Auteur { get; set; }
}
为什么不将AuteurId属性添加到实体类中。通过这种方式,您将避免在获取用户实体(UserManager.FindById(User.Identity.GetUserId())
)的其他查询。
public class Blog
{
[Key]
public int Id { get; set; }
[Required]
// etc
public string Titel { get; set; }
public string Beschrijving { get; set; }
public bool Content { get; set; }
public bool Verwijderd { get; set; }
[ForeignKey("Auteur")]
public string AuteurId { get; set; }
public virtual ApplicationUser Auteur { get; set; }
}
然后在您的操作代码中就像
_blogService.Insert(new Blog()
{
Titel = vm.Titel,
Beschrijving = vm.Beschrijving,
Content = (vm.Actie.ToLower() == "publiceer" ? true : false),
Verwijderd = false,
AuteurId = User.Identity.GetUserId()
});