我有一个与新的InputOutputMap相关的新ParameterPart实体。 InputOutputMap有几个InputStates,我从数据库中提取,我需要与InputOutputMap关联。如何使用MVC和WCF数据服务将此链保存到数据库?我使用以下代码(通过ajax调用调用,上下文仅在构造函数的第一次调用中设置)但是我遇到了几个问题:
当我在方法中设置上下文而不是构造函数时,我没有任何好处。
if (vm != null)
{
ParameterPart parameterPart = null;
// Create a new parameter
if (vm.PartNumberId == 0)
{
// Create an instance of ParameterPart
parameterPart = new ParameterPart()
{
Description = vm.ParameterDescription
};
// Save the ParameterPart into the database
try
{
ctx.AddToParameterParts(parameterPart);
ctx.SaveChanges();
}
catch (System.Exception ex)
{
throw;
}
}
else
{
// Fetch the existing parameter
parameterPart = new ParameterPart();
parameterPart = (from pp in ctx.ParameterParts
where pp.PartNumberId == vm.PartNumberId
select pp).Single();
// Update the ParameterPart from the vm
parameterPart.Description = vm.ParameterDescription;
}
if (parameterPart != null)
{
if (vm.StateValues.Count > 0)
{
InputOutputMap inputOutputMap = new InputOutputMap();
inputOutputMap.PartNumberId = parameterPart.PartNumberId;
ctx.AddToInputOutputMaps(inputOutputMap);
// Prepare a new InputOutputMap
foreach (var state in vm.StateValues)
{
if (state.InputStateId != 0)
{
// Fetch the inputstate
var inputState = (from i in ctx.InputStates
where i.InputStateId == state.InputStateId
select i).Single();
try
{
ctx.AddLink(inputOutputMap, "InputStates", inputState);
ctx.SaveChanges();
}
catch (System.Exception ex)
{
throw;
}
}
}
}
}
}
答案 0 :(得分:0)
AddLink方法正在按预期工作。由于数据问题,我收到了错误。