简体   繁体   English

EntityFramework更新具有相关对象的实体

[英]EntityFramework update entity with related objects

I have a Project entity and a Rule entity. 我有一个Project实体和一个Rule实体。 A project can have many rules. 一个项目可以有很多规则。

Edit 1: Here is the relation we have defined. 编辑1:这是我们定义的关系。 Sorry for not using plural in the navigation property, we haven't updated it yet. 抱歉,在导航属性中未使用复数形式,我们尚未对其进行更新。

在此处输入图片说明

So I have this method: 所以我有这种方法:

    public bool Update(Project project)
    {
        Logger.Log(GetType(), string.Format("Updating project {0}", project));
        using (var ctx = new EntityModelContainer())
        {

            if (project.Id == 0)
            {
                return false;
            }

            try
            {
                ctx.ProjectSet.Attach(project);
                ctx.Entry(project).State = EntityState.Modified;
                return ctx.SaveChanges() >= 1;
            }
            catch (Exception exc)
            {
                throw new ComplianceException(exc.Message, exc);
            }
        }
    }

It will update all scalar attributes of a project. 它将更新项目的所有标量属性。 But if I add or delete a rule to a project and run Update(project) , it is not considered. 但是,如果我向项目添加或删除规则并运行Update(project) ,则不会考虑。 Why? 为什么?

Edit 2: I have also tried to re-read the project and assign the updated values. 编辑2:我也尝试过重新阅读该项目并分配更新的值。 Please notice that projectRead.Rule is a list. 请注意, projectRead.Rule是一个列表。

    public bool Update(Project projectGiven)
    {
        // Add all changes here
        Project projectRead = this.ReadProject(projectGiven.Id);
        if (projectRead == null)
        {
            Logger.Log(GetType(), "Project not found");
            return false;
        }

        projectRead.ProjectName = projectRead.ProjectName;
        projectRead.Report = projectRead.Report;
        projectRead.Rule = projectRead.Rule;

        Logger.Log(GetType(), string.Format("Updating project {0}", projectRead));
        using (var ctx = new EntityModelContainer())
        {
            ...

Thank you very much! 非常感谢你!

Seems to me that with latest version of entity framework, and entity is not added automatically to the change tracker if assigned to and entity that is already in the change tracker. 在我看来,使用最新版本的实体框架,如果将实体分配给了变更跟踪器中已经存在的实体,则不会自动将其添加到变更跟踪器中。

Obviously this depends on the way role and project are related. 显然,这取决于角色和项目之间的关联方式。

I suppose the more simple way si to create a procedure that reload the project including all the roles, delete the selected one from the list, and after to save it, at this point I think al the updates are done correrctly. 我想用一种更简单的方法来创建一个过程,该过程重新加载包括所有角色的项目,从列表中删除选定的角色,然后保存它,此时,我认为所有更新均已正确完成。

I solved the problem. 我解决了问题。 I need to reload the project within the same context before I update. 我需要在相同的上下文中重新加载项目,然后再进行更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM