Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# instert引用多个实例的实体,并将其与EF一起放入数据库中_C#_Asp.net Mvc_Entity Framework_Invalidoperationexception - Fatal编程技术网

C# instert引用多个实例的实体,并将其与EF一起放入数据库中

C# instert引用多个实例的实体,并将其与EF一起放入数据库中,c#,asp.net-mvc,entity-framework,invalidoperationexception,C#,Asp.net Mvc,Entity Framework,Invalidoperationexception,我将使用Entity Framework和ASP.NET MVC应用程序在数据库中插入一个博客。如果我想将实体添加到上下文中,我在下面代码的最后一行遇到了这个错误 InvalidOperationException:一个实体对象不能被IEntityChangeTracker的多个实例引用 这是我的密码: public class AdminController : Controller { [HttpPost] public ActionResult CreateBlog(Blo

我将使用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
    }
}
公共类AdminController:控制器
{
[HttpPost]
public ActionResult CreateBlog(BlogViewModel虚拟机)
{
尝试
{
_插入(新博客()
{
滴度=vm.Titel,
Beschrijving=vm.Beschrijving,
Content=(vm.Actie.ToLower()=“publiceer”?true:false),
Verwijderd=false,
Auteur=UserManager.FindById(User.Identity.GetUserId())
});
}
捕获(例外情况除外)
{
控制台。写入(例如消息);
}
返回重定向到操作(博客名称);
}
公共应用程序管理员用户管理器
{
得到
{
返回_userManager??HttpContext.GetOwinContext().GetUserManager();
}
专用设备
{
_userManager=value;
}
}
公共AdminController(ApplicationUserManager用户管理器、IBlogService博客)
{
UserManager=UserManager;
_blogService=blog;
}
}
公共类BlogService:IBlogService
{
公共空白插入(博客)
{
_blogRepo.Insert(blog);
_blogRepo.SaveChanges();
}
}
公共类BlogRepo:GenericRepo
{
公共覆盖博客插入(博客)
{
context.Entry(blog.Auteur).State=EntityState.Unchanged;
在这一行返回dbSet.Add(blog);//-->
}
}

你能帮我找到我的问题吗?提前感谢。

我想您的实体模型如下所示:

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())

然后在你的行动代码中

_blogService.Insert(new Blog()
{
   Titel = vm.Titel,
   Beschrijving = vm.Beschrijving,
   Content = (vm.Actie.ToLower() == "publiceer" ? true : false),
   Verwijderd = false,
   AuteurId = 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; }

    public ApplicationUser Auteur { get; set; }
}
为什么不将AuteurId属性添加到实体类中呢。通过这种方式,您将避免在获取用户实体的地方进行额外的查询(
UserManager.FindById(user.Identity.GetUserId())

然后在你的行动代码中

_blogService.Insert(new Blog()
{
   Titel = vm.Titel,
   Beschrijving = vm.Beschrijving,
   Content = (vm.Actie.ToLower() == "publiceer" ? true : false),
   Verwijderd = false,
   AuteurId = User.Identity.GetUserId()
});

userManager和blogService是否共享相同的dbContext。如果不是,则用户被2个上下文保留。每个请求应该有一个且只有一个上下文实例。将其定义为控制器上的私有字段,并手动将其注入
UserManager
BlogService
实例,或者使用依赖项注入容器来管理生存期和注入。@tschmit007:不,每次只有一个
dbContext
。我们如何确定这一点,如何实例化控制器(构造函数)和/或注入依赖项?userManager和blogService是否共享相同的dbContext。如果不是,则用户被2个上下文保留。每个请求应该有一个且只有一个上下文实例。将其定义为控制器上的私有字段,并手动将其注入
UserManager
BlogService
实例,或者使用依赖项注入容器来管理生存期和注入。@tschmit007:不,每次只有一个
dbContext
。我们如何确定这一点,如何实例化控制器(构造函数)和/或注入依赖项?是的。因为它是两次被跟踪的
ApplicationUser-Auteur
。一次是根据UserManger的上下文,一次是在添加博客时根据存储库的上下文。是。因为它是两次被跟踪的
ApplicationUser-Auteur
。一次是通过UserManger的上下文,另一次是在添加博客时通过存储库的上下文。