我有两个名为GetControllerBlocks()
的实体。
请参阅ControllerName ActionName
-------------- ------------
Home Index
Home DasBoard
Home Chart
HR Leave
HR Loan
Payroll view
Payroll Edit
Payroll Process
函数,然后您就可以了解我如何填充两个类的数据,如主细节。如何使用EF将这两个实体的数据存储到一个表中?
表格结构如
public class ControllerBlock
{
public string ControllerName { get; set; }
public List<ControllerAction> ControllerActions { get; set; }
}
public class ControllerAction
{
public string ActionName { get; set; }
}
public List<ControllerBlock> GetControllerBlocks()
{
// Set ActionActive herem, if necessary
List<ControllerAction> homeActions = new List<ControllerAction>() {
new ControllerAction { ActionName = "Index" },
new ControllerAction { ActionName = "DashBoard" },
new ControllerAction { ActionName = "Chart" }
};
List<ControllerAction> hrActions = new List<ControllerAction>() {
new ControllerAction { ActionName = "Leave" },
new ControllerAction { ActionName = "Loan" },
new ControllerAction { ActionName = "NoticeBoard" }
};
List<ControllerAction> payRollActions = new List<ControllerAction>() {
new ControllerAction { ActionName = "View" },
new ControllerAction { ActionName = "Edit" },
new ControllerAction { ActionName = "Process" }
};
List<ControllerBlock> actionBlocks = new List<ControllerBlock>()
{
new ControllerBlock(){ControllerName = "Home", ControllerActions = homeActions},
new ControllerBlock(){ControllerName = "HR", ControllerActions = hrActions},
new ControllerBlock(){ControllerName = "PayRoll", ControllerActions = payRollActions}
};
return actionBlocks;
}
我的示例代码:
C-x C-s
我首先使用EF代码,因此当我有两个实体时,建议在一个表中插入数据的最佳方法。如果可能,添加一些代码提示,以便将数据从两个类插入到一个表中。感谢
答案 0 :(得分:0)
您基本上想要将数据展平为一个序列。这可以使用SelectMany
完成。
基于表结构,假设实体看起来像
public class Entity {
public string ControllerName { get; set; }
public string ActionName { get; set; }
}
基于提供的模型。
var actionBlocks = GetControllerBlocks();
//Flatten the collection of block.
List<Entity> controllerActions = actionBlocks
.SelectMany(b => b.ControllerActions
.Select(a => new Entity {
ControllerName = b.ControllerName,
ActionName = a.ActionName
})
)
.ToList();
从那里你应该可以将所有东西保存到一张桌子上。