在foreach中更新变量

时间:2014-01-27 08:42:11

标签: c#

我遇到了一个与通过引用更新对象有关的问题,但不确定究竟发生了什么。

我需要删除规则列表,对于日志记录,我需要加载另一个字段

ruleItem.ReferencedItemValue = eventEntity.Title;

 builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");

被称为ReferencedItemValue未填充。

任何想法,建议和替代方案? 感谢

CODE:

public void DeleteCustomLogicRule(int[] ruleIds){
    var rules = uow.Context.ShowRules.Where(sr => ruleIds.Contains(sr.Id)).ToList();
    if (rules.Any())
    {
        var showId = rules.FirstOrDefault().ShowId;
        var builder = AuditBuilder.FromShowId(showId);
        rules.ForEach(showRule =>
        {
            var showRuleResource = ToShowRuleResource(showRule);
            FillReferenceValue(showRuleResource);
            builder.LogDelete(showRule, showRuleResource.ToAuditLog(), "Logic Rule");
            });
        uow.Context.SaveChanges();
        builder.ToDatabase();
    }
}

private void FillReferenceValue(ShowRuleResource showRuleResource)
{
    foreach (var ruleItem in showRuleResource.ItemsPredicateAppliesTo.ToList())
    {
        FillRuleItem(ruleItem);
    }
}

private void FillRuleItem(RuleItemResource ruleItem)
{
    var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);
    if (eventEntity != null)
    ruleItem.ReferencedItemValue = eventEntity.Title;
}

2 个答案:

答案 0 :(得分:1)

试试这个:

rules.ForEach(showRule =>
    {
        var item = showRule;
        var showRuleResource = ToShowRuleResource(item);
        FillReferenceValue(showRuleResource);
        builder.LogDelete(item, showRuleResource.ToAuditLog(), "Logic Rule");
        });

答案 1 :(得分:1)


从这个功能开始挖掘

private void FillRuleItem(RuleItemResource ruleItem)

这似乎是这种解决方法

var eventEntity = uow.Context.Events.FirstOrDefault(e => e.Id == ruleItem.ReferencedItemId.Value);

为空。