0

Given 3 database tables:

A (id, type, code, ...)
B (code, text)
C (id, key, val)

A.code == B.code
A.id == C.id (C.id is not a unique key, multiple entries are possible)

B.text might contain replacement variables, in the form $KEY$. (So, for example, it might contain: "This is a $SOMEKEY$". C might contain the key and a replacement value:

$SOMEKEY$: Message
$SOMEOTHERKEY$: Text

Currently I perform the replacement in two steps. First, I get all the required data:

var result = from a in context.A where a.type == myType
             join b in context.B on a.code == b.code
             select new {
                 ID = a.id,
                 Code = a.code,
                 Text = b.Text
             };

Next, I get all matching replacement variables. It might be that there is no key available in C.

var data = context.C.Where(c => result.Select(r => r.ID).Contains(c));

Then I loop over the lists and perform the replacement:

foreach (var r in result) {
    var local = r;
    foreach (var c in data.Where(c => c.id == local.ID)) {
        local.Text = local.Text.Replace(c.key, c.val);
    }
}

Now, aside from any database compatibility issues and readability aside, would it be possible to perform the search and replace within the first database query?

4

1 回答 1

0

真正有问题的是您需要对同一个变量应用多个替换,而我在 Linq 中看不到这样做的方法。

但是,您可以做的是将它从两个查询和一个 foreach 循环减少到一个查询和一个 foreach 循环:

// group by the replacement string and gather all the replacements
var result = from a in context.A
    join b in context.B on a.code equals b.code
    join c in context.C on a.id equals c.id
    group new {b.text, c.key, c.val} by b.code into grp
    select grp;


// loop through each group and apply replacements
foreach(var r in result) {
    var text = r.First().text;

    foreach(var c in r) {
        text = text.Replace(c.key, c.val);
    }
}

目前尚不清楚您的哪些字段是主键以及哪些字段是唯一的,但我相信您应该能够找到一个查询,该查询至少包含您需要处理的所有数据,并且您可以避免做第二个查询。您可能需要调整分组内容和分组依据。

于 2013-08-24T21:48:58.607 回答