在Entity Framework中保存已编辑的对象

时间:2010-09-06 05:57:26

标签: c# 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();
        }

方法exectues没有例外。但在数据库中没有任何变化我必须改变什么?

这是我的恩赐:

    [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
}

3 个答案:

答案 0 :(得分:3)

EF上下文跟踪实体更改 - 因此,如果您正在分离/附加实体,则不会跟踪更改。现在,当您尝试通过附加到上下文来更新实体时,从上下文角度来看,实体没有任何更改。因此SaveChanges不会尝试保存任何东西。在调用SaveChanges方法之前,您必须以某种方式将对象标记为脏或更改。请参考this blog post以实现它。这里是yet another post概述类似的解决方案。

答案 1 :(得分:1)

这取决于您检索要编辑的项目的方式。如果按照GetProjectById方法获取它,那么该项目实体正在通过相关的ObjectContext跟踪它的更改。

来自MSDN

  

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

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

我建议使用Repository模式来管理您的ObjectContexts,以便您拥有正确的ObjectContext跟踪并保存更改。

答案 2 :(得分:1)

你有两个选择。首选是在GetProjectById和SaveProject之间共享上下文。您的实体将跟踪更改,您无需调用Attach。如果您希望/需要为每个操作打开新的上下文,您必须告诉上下文Project已被修改。当实体附加到上下文时,它将被跟踪为未更改。您必须在附加后调用ObjectStateManager手动将实体状态更改为已修改:

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

顺便说一下。 ObjectContext是一次性的,所以你应该通过使用或try / finally来处理它。

修改

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