繁体   English   中英

在实体框架中保存编辑后的对象

[英]Saving edited object in Entity Framework

我的实体中有对象Project。 我通过以下方式创建项目:

 public static void Add(Project project)
        {
            var context = new Entities();
            context.AddToProjects(project);

            context.SaveChanges();
        }

接下来,我得到这个对象:

 public static Project GetProjectById(int idProject)
        {
            var context = new Entities();
            return context.Projects.Where(p => p.IDProject == idProject).First();
        }

并且这两种方法都能正常工作。

但是,当我想通过以下方式保存编辑后的任务时:

public static void SaveProject(Project project)
        {
            var context = new Entities();
            project.EntityKey = new EntityKey("Entities.Projects", "IDProject", project.IDProject);
            context.Attach(project);
            context.SaveChanges();
        }

方法无例外地执行。 但是,数据库中没有任何变化。 我必须改变什么?

这是我的实体:

    [EdmEntityTypeAttribute(NamespaceName="GWDModel", Name="Project")]
    [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Project : EntityObject
    {
        #region Factory Method

    /// <summary>
    /// Create a new Project object.
    /// </summary>
    /// <param name="iDProject">Initial value of the IDProject property.</param>
    /// <param name="name">Initial value of the Name property.</param>
    /// <param name="expectedCost">Initial value of the ExpectedCost property.</param>
    /// <param name="status">Initial value of the Status property.</param>
    public static Project CreateProject(global::System.Int32 iDProject, global::System.String name, global::System.Decimal expectedCost, StatusOfProjectWrapper status)
    {
        Project project = new Project();
        project.IDProject = iDProject;
        project.Name = name;
        project.ExpectedCost = expectedCost;
        project.Status = StructuralObject.VerifyComplexObjectIsNotNull(status, "Status");
        return project;
    }

    #endregion
    #region Primitive Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int32 IDProject
    {
        get
        {
            return _IDProject;
        }
        set
        {
            if (_IDProject != value)
            {
                OnIDProjectChanging(value);
                ReportPropertyChanging("IDProject");
                _IDProject = StructuralObject.SetValidValue(value);
                ReportPropertyChanged("IDProject");
                OnIDProjectChanged();
            }
        }
    }
    private global::System.Int32 _IDProject;
    partial void OnIDProjectChanging(global::System.Int32 value);
    partial void OnIDProjectChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.String Name
    {
        get
        {
            return _Name;
        }
        set
        {
            OnNameChanging(value);
            ReportPropertyChanging("Name");
            _Name = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("Name");
            OnNameChanged();
        }
    }
    private global::System.String _Name;
    partial void OnNameChanging(global::System.String value);
    partial void OnNameChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Decimal ExpectedCost
    {
        get
        {
            return _ExpectedCost;
        }
        set
        {
            OnExpectedCostChanging(value);
            ReportPropertyChanging("ExpectedCost");
            _ExpectedCost = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("ExpectedCost");
            OnExpectedCostChanged();
        }
    }
    private global::System.Decimal _ExpectedCost;
    partial void OnExpectedCostChanging(global::System.Decimal value);
    partial void OnExpectedCostChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
    [DataMemberAttribute()]
    public Nullable<global::System.DateTime> PlannedStart
    {
        get
        {
            return _PlannedStart;
        }
        set
        {
            OnPlannedStartChanging(value);
            ReportPropertyChanging("PlannedStart");
            _PlannedStart = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("PlannedStart");
            OnPlannedStartChanged();
        }
    }
    private Nullable<global::System.DateTime> _PlannedStart;
    partial void OnPlannedStartChanging(Nullable<global::System.DateTime> value);
    partial void OnPlannedStartChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
    [DataMemberAttribute()]
    public Nullable<global::System.DateTime> PlannedEnd
    {
        get
        {
            return _PlannedEnd;
        }
        set
        {
            OnPlannedEndChanging(value);
            ReportPropertyChanging("PlannedEnd");
            _PlannedEnd = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("PlannedEnd");
            OnPlannedEndChanged();
        }
    }
    private Nullable<global::System.DateTime> _PlannedEnd;
    partial void OnPlannedEndChanging(Nullable<global::System.DateTime> value);
    partial void OnPlannedEndChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
    [DataMemberAttribute()]
    public Nullable<global::System.DateTime> DateOfStart
    {
        get
        {
            return _DateOfStart;
        }
        set
        {
            OnDateOfStartChanging(value);
            ReportPropertyChanging("DateOfStart");
            _DateOfStart = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("DateOfStart");
            OnDateOfStartChanged();
        }
    }
    private Nullable<global::System.DateTime> _DateOfStart;
    partial void OnDateOfStartChanging(Nullable<global::System.DateTime> value);
    partial void OnDateOfStartChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
    [DataMemberAttribute()]
    public Nullable<global::System.DateTime> DateOfEnd
    {
        get
        {
            return _DateOfEnd;
        }
        set
        {
            OnDateOfEndChanging(value);
            ReportPropertyChanging("DateOfEnd");
            _DateOfEnd = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("DateOfEnd");
            OnDateOfEndChanged();
        }
    }
    private Nullable<global::System.DateTime> _DateOfEnd;
    partial void OnDateOfEndChanging(Nullable<global::System.DateTime> value);
    partial void OnDateOfEndChanged();

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
    [DataMemberAttribute()]
    public Nullable<global::System.Decimal> CurrentCost
    {
        get
        {
            return _CurrentCost;
        }
        set
        {
            OnCurrentCostChanging(value);
            ReportPropertyChanging("CurrentCost");
            _CurrentCost = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("CurrentCost");
            OnCurrentCostChanged();
        }
    }
    private Nullable<global::System.Decimal> _CurrentCost;
    partial void OnCurrentCostChanging(Nullable<global::System.Decimal> value);
    partial void OnCurrentCostChanged();

    #endregion
    #region Complex Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmComplexPropertyAttribute()]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    [XmlElement(IsNullable=true)]
    [SoapElement(IsNullable=true)]
    [DataMemberAttribute()]
    public StatusOfProjectWrapper Status
    {
        get
        {
            _Status = GetValidValue(_Status, "Status", false, _StatusInitialized);
            _StatusInitialized = true;
            return _Status;
        }
        set
        {
            OnStatusChanging(value);
            ReportPropertyChanging("Status");
            _Status = SetValidValue(_Status, value, "Status");
            _StatusInitialized = true;
            ReportPropertyChanged("Status");
            OnStatusChanged();
        }
    }
    private StatusOfProjectWrapper _Status;
    private bool _StatusInitialized;
    partial void OnStatusChanging(StatusOfProjectWrapper value);
    partial void OnStatusChanged();

    #endregion

    #region Navigation Properties

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [XmlIgnoreAttribute()]
    [SoapIgnoreAttribute()]
    [DataMemberAttribute()]
    [EdmRelationshipNavigationPropertyAttribute("GWDModel", "FK_ProjectChanges_Projects", "ProjectChanges")]
    public EntityCollection<ProjectChanx> ProjectChanges
    {
        get
        {
            return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<ProjectChanx>("GWDModel.FK_ProjectChanges_Projects", "ProjectChanges");
        }
        set
        {
            if ((value != null))
            {
                ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<ProjectChanx>("GWDModel.FK_ProjectChanges_Projects", "ProjectChanges", value);
            }
        }
    }

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [XmlIgnoreAttribute()]
    [SoapIgnoreAttribute()]
    [DataMemberAttribute()]
    [EdmRelationshipNavigationPropertyAttribute("GWDModel", "ProjectManagers", "Users")]
    public EntityCollection<User> Users
    {
        get
        {
            return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<User>("GWDModel.ProjectManagers", "Users");
        }
        set
        {
            if ((value != null))
            {
                ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<User>("GWDModel.ProjectManagers", "Users", value);
            }
        }
    }

    /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [XmlIgnoreAttribute()]
    [SoapIgnoreAttribute()]
    [DataMemberAttribute()]
    [EdmRelationshipNavigationPropertyAttribute("GWDModel", "FK_Milestones_Projects", "Milestone")]
    public EntityCollection<Milestone> Milestones
    {
        get
        {
            return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Milestone>("GWDModel.FK_Milestones_Projects", "Milestone");
        }
        set
        {
            if ((value != null))
            {
                ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Milestone>("GWDModel.FK_Milestones_Projects", "Milestone", value);
            }
        }
    }

    #endregion
}

EF上下文跟踪实体更改-因此,如果要分离/附加实体,则不会跟踪更改。 现在,当您尝试通过附加到上下文来更新实体时,从上下文的角度来看,实体没有任何更改。 因此,SaveChanges不会尝试保存任何东西。 您必须以某种方式将对象标记为脏或已更改,然后再调用SaveChanges方法。 请参阅此博客文章以实现它。 这是概述类似解决方案的另一篇文章

这取决于您如何检索要编辑的项目。 如果按照GetProjectById方法获取数据,则该项目实体将通过相关的ObjectContext跟踪其更改。

MSDN

实体框架跟踪对附加到ObjectContext的对象的更改。 实体数据模型工具生成一对名为OnPropertyChanging和OnPropertyChanged的局部方法。 这些方法在属性设置器中调用。

基本上,将更改保存到跟踪的实体所需要做的就是在从中提取对象的同一对象上下文中调用SaveChanges()方法。

我建议您考虑使用存储库模式来管理ObjectContext,以便您具有正确的ObjectContext跟踪并保存更改。

您有两种选择。 首选是在GetProjectById和SaveProject之间共享上下文。 比您的实体将跟踪更改,您将不需要致电Attach。 如果要/需要为每个操作打开新的上下文,则必须告诉上下文Project已被修改。 当实体附加到上下文时,其被跟踪为“不变”。 附加后,您必须通过调用ObjectStateManager来手动将实体状态更改为修改状态:

context.ObjectStateManager.ChangeObjectState(project, EntityState.Modified);

顺便说一句。 ObjectContext是一次性的,因此您应该使用或试试/最终处理它。

编辑:

根据您对WCF的评论,第一选择是不可能的。 但是您也可以检查自我跟踪实体(仅EF 4.0)。

暂无
暂无

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

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