我有一个具有以下方法的 Controller getMail():
public JsonResult getMail(string id)
{
int Id = Convert.ToInt32(id);
string pattern = @"\bmem_id\b";
string replace = "100";
var result = (from a in db.tblmail_type
where a.Id == Id
select new MailModel
{
subject = a.Subject,
Content = Regex.Replace(a.Content, pattern, replace);
});
return Json(result, JsonRequestBehavior.AllowGet);
}
该方法用于获取邮件内容。在获取内容之前,我想将邮件内容中的一个“mem_id”替换为“100”。默认内容如下:
Content = "You have successfully registered with Member ID: mem_id"
我在 LINQ 中使用了 Regex.Replace()
方法。但是这段代码并没有改变内容。当我将此代码更改为下面给出的这种形式时,它可以正常工作。
public JsonResult getMail(string id)
{
int Id = Convert.ToInt32(id);
var input = db.tblmail_type.Where(x=>x.Id==Id).FirstOrDefault().Content;
string pattern = @"\bmem_id\b";
string replace = "100";
string content = Regex.Replace(input, pattern, replace);
var result = (from a in db.tblmail_type
where a.Id == Id
select new MailModel
{
subject = a.Subject,
Content = content
});
return Json(result, JsonRequestBehavior.AllowGet);
}
为什么会这样?任何人都可以指定这个奇怪问题背后的原因吗?如何替换 LINQ 中的“内容”?
最佳答案
您可以使用以下任何一种解决方案,
解决方案 1:
不幸的是,您无法将正则表达式处理逻辑直接发送到数据库。
您需要从数据库中获取 Content
,然后遍历列表并应用正则表达式。
这可以通过使用 AsEnumerable()
来完成。它将查询分为两部分。
第一部分是内部
(AsEnumerable() 之前的查询)作为Linq-to-SQL
执行。
第二部分是外部部分
(AsEnumerable() 之后的查询)作为Linq-to-Objects
执行。
第一部分在数据库上执行,所有数据都被带到客户端。
第二部分(这里是选择)在客户端执行。
所以简而言之,AsEnumerable()
运算符将查询处理移至客户端。
var result = ( from a in db.tblmail_type.AsEnumerable()
where a.Id == Id
select new MailModel {
subject = a.Subject,
Content = Regex.Replace(a.Content, pattern, replace)
});
解决方案 2:
var result = db.tblmail_type.Where(x => x.Id == Id).AsEnumerable().Select(x => new MailModel { Content = Regex.Replace(x.Content, pattern, replace) , subject = x.Subject}).ToList();
解决方案 3:
var result = db.tblmail_type.Where(x => x.Id == Id).ToList();
result.ForEach(x => x.Content = Regex.Replace(x.Content, pattern, replace));
关于c# - 我如何在 LINQ 中使用 Regex.Replace 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585784/