比较两个对象以检查它们是否不同

时间:2016-10-11 17:21:27

标签: c#-4.0 entity-framework-5

我有一个接受两个参数的方法。 Projecthealthnotes是我的模型。

我想将objprojHealth与我从数据库中检索的getRow对象进行比较。

如果它们相同则无需调用SaveChanges(),如果不相同则调用SaveChanges()

如何比较这两个对象并检查它们是否相同?

            public string WriteProgressHealthInfoToDb(Projecthealthnotes objprojHealth, string typeOfOperation)
                    {
                        using (var dbCntxt = new PPMSEntities1())
                        {

                                tbl_Project_Status_MSTR psmTable;               
                                var convertedId = Convert.ToInt64(objprojHealth.Id);
                                var getRow = dbCntxt.tbl_Project_Status_MSTR.Single(m => m.ProjectStatusID == convertedId);

                                getRow.RecentProgress = objprojHealth.Recentprogress;
                                getRow.ObstaclesRisks = objprojHealth.Obstaclesrisk;
                                getRow.NextSteps = objprojHealth.Nextsteps;
                                getRow.ForWeekEnding = Convert.ToDateTime(objprojHealth.Weekendingdate);
                                getRow.BudgetHealth = Translator(objprojHealth.BudgetHealth);
                                getRow.TeamHealth = Translator(objprojHealth.TeamHealth);
                                getRow.RiskHealth = Translator(objprojHealth.RiskHealth);
                                getRow.ArtifactHealth = Translator(objprojHealth.BenefitHealth);
                                getRow.ScopeHealth = Translator(objprojHealth.ScopeHealth);
                                getRow.ScheduleHealth = Translator(objprojHealth.ScheduleHealth);
                                getRow.Phase = objprojHealth.Phase;
                                getRow.ReportingPeriod = Convert.ToInt16(objprojHealth.Reportingperiod);

                                //dbCntxt.Entry(getRow).State = System.Data.Entity.EntityState.Modified;

                                dbCntxt.SaveChanges();

                            return "success";

                        }

1 个答案:

答案 0 :(得分:0)

执行此操作的唯一方法是编写一个使用反射来比较每个属性的函数。根据您的对象,如果它具有嵌套的引用类型,您可能需要做一些更复杂的事情。以下链接有一些例子

http://www.sidesofmarch.com/index.php/archive/2007/08/03/use-reflection-to-compare-the-properties-of-two-objects/