簡體   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