我必须更新专栏' PPMOProjectID'在表中,但是如果它是空的并且棘手的部分是
我在表格中只有父子关系的范围,如果MP-主父母,P-父母,孩子 - C:
ID ParentID PPMOProjectID
MP1 NULL NULL //updating here by 889
P1 MP1 898 //It should not update, because it contains already value
P2 MP1 NULL//it should update by 889 if it is empty else skip it
C1 P1 NULL//Here it should update by 898
C2 P1 NULL//Here it should update by 898
C3 P2 NULL//Here it should update by 889
按照上述逻辑:当我在父记录中更新PPMOProjectID时,我必须检查所有孩子和主孩子,如果记录为空我必须通过立即记录父母更新,它parent为空,需要按主列ID更新,如果父记录具有列ID,则应按父ID本身更新。
这应该在C#和LINQ中完成,我尝试过以下逻辑:
var childProjects = db.Projects.Where(m => m.AC_ParentProject_ID == AC_ProjectID).ToList();
var updateRecords = new List<Project>();
while (childProjects.Count == 0)
{
foreach(var item in childProjects)
{
updateRecords = childProjects.Where(m => m.AC_ParentProject_ID == item.AC_ParentProject_ID).ToList();
//saving logic here..
}
}
但如何让大孩子继续检查。
我正在努力寻找满足上述要求的方法。任何人都可以请帮助。
答案 0 :(得分:1)
您可以从主行(MP)开始,然后向下迭代父行(P)并更新它们(需要它的地方,即如果PPMOProjectID
为空)。对于父级的每次迭代,您可以在其子级(C)中输入新的迭代,并使用父级PPMOProjectID
更新其PPMOProjectID
(如果它不为空),因为父级已经PPMOProjectID
具有分配给它的正确值。
在下面的代码中,我使用了您在表格中定义的名称。如果您的实体中有不同的名称,则可以相应地更改它们。您可能不需要的前四行可能已经涵盖了检索主记录和设置其PPMOProjectID的逻辑,但为了清楚起见,我添加它们。
string AC_ProjectID = "MP1"; // you might be getting this value from somewhere else and not declaring it like this
string parentPPMOID = "889"; // the value which you are updating
var masterParent = db.Projects.FirstOrDefault(p => p.ID == AC_ProjectID); //get the master parent itself
masterParent.PPMOProjectID = parentPPMOID;
var parentProjects = db.Projects.Where(m => m.ParentID == AC_ProjectID).ToList();
foreach(var parentProject in parentProjects)
{
if(parentProject.PPMOProjectID == null)
{
// assign the PPMOProjectID to the parent
parentProject.PPMOProjectID = masterParent.PPMOProjectID;
}
var childProjects = db.Projects.Where(c => c.ParentID == parentProject.ID).ToList();
foreach(var childProject in childProjects)
{
if(childProject == null)
{
//assign the child PPMOProjectID with the parent PPMOProjectID since it already was set in line 11 (of this code snippet)
childProject.PPMOProjectID = parentProject.PPMOProjectID;
}
}
}
//saving logic here..
修改强> 如果深度可以继续,您可以使用递归来尽可能多地向孩子们求助。以下方法可以解决您的问题。
public void UpdatePPMORecursively(Project project, string ppmo)
{
if (project.PPMOProjectID == null)
{
project.PPMOProjectID = ppmo;
}
var childrenProjects = db.Projects.Where(c => c.AC_ParentProject_ID == project.ID).ToList();
if (childrenProjects.Count() == 0)
{
return;
}
foreach (var childProject in childrenProjects)
{
UpdatePPMORecursively(childProject, project.PPMOProjectID);
}
}
你可以用这样的方法调用方法。我将使用与以前相同的上下文变量:
string AC_ProjectID = "MP1"; // you might be getting this value from somewhere else and not declaring it like this
string parentPPMOID = "889"; // the value which you are updating
var masterParent = db.Projects.FirstOrDefault(p => p.ID == AC_ProjectID); //get the master parent itself
UpdatePPMORecursively(masterParent, parentPPMOID );
请注意,性能方面,它可能不是世界上最好的解决方案,因为您正在处理数据库。