public CurveConstituent AddRiskFactorDimItemDetail(RiskFactorDimItemDetail item, CurveDetail curve, RiskFactorDimension dimension) { var existingDim = curve.Curve.CurveDimensions.FirstOrDefault(x => x.RiskFactorDimensionID == dimension.RiskFactorDimensionID); CurveConstituent persisted = null; if (existingDim != null) { persisted = existingDim.CurveConstituents.Where(x => x.RiskFactorDimItemID == item.RiskFactorDimItemID && x.CurveDimension.RiskFactorDimensionID == dimension.RiskFactorDimensionID && x.CurveDimension.CurveID == curve.CurveID).FirstOrDefault(); } if (persisted != null && Context.Entry(persisted).State == EntityState.Modified) { // remove any changes Context.Entry(persisted).State = EntityState.Unchanged; return persisted; } var detail = new CurveConstituent(); detail.Default(Context.UserName); detail.CurveConstituentID = Context.CurveConstituents.Count() > 0 ? Context.CurveConstituents.Max(x => x.CurveConstituentID) + 1 : 1; var dim = curve.Curve.CurveDimensions.FirstOrDefault(x => x.RiskFactorDimensionID == dimension.RiskFactorDimensionID); if (dim == null) { var newDim = new CurveDimension(); newDim.Approve(Context.UserName); newDim.CurveDimensionID = Context.CurveDimensions.Count() > 0 ? Context.CurveDimensions.Max(x => x.CurveDimensionID) + 1 : 1; newDim.Default(Context.UserName); newDim.RiskFactorDimensionID = dimension.RiskFactorDimensionID; detail.CurveDimension = newDim; newDim.Curve = curve.Curve; curve.Curve.CurveDimensions.Add(newDim); Context.CurveDimensions.Add(newDim); } else { detail.CurveDimension = dim; } detail.RiskFactorDimItem = item.RiskFactorDimItem; Context.CurveConstituents.Add(detail); return detail; }