【问题标题】:How can i use Custom query Single field in EFCore?如何在 EFCore 中使用自定义查询单字段?
【发布时间】:2020-11-03 10:24:33
【问题描述】:
  1. 在 EF6 中,我可以使用 context.Database.sqlquery。为什么 EF Core 取消这个?
  2. 我试图找到答案,但context.user.FromInterpolated 不允许选择单个字段。 (还是我使用了错误的方法?)
  3. 这是我的代码。请给我一些建议,我可以解决这个问题。
[HttpPost]
[Obsolete]
public async Task<IActionResult> SendEmail()
{
    Email email = new Email();
    var ID = HttpContext.Request.Form["ID"].ToString();
    var Title = HttpContext.Request.Form["Title"].ToString();
    var Body = HttpContext.Request.Form["Body"].ToString();
    var Emails = context.user.FromSqlInterpolated($"select email from user where UserId in({ID})");
    foreach (var item in Emails)
    {
        if (!string.IsNullOrEmpty(item.Email))
        {
            email.Send(item.Email, Title, Body);
        }
    }
    await HttpResponseWritingExtensions.WriteAsync(this.Response, "success");
    return RedirectToAction(nameof(Index));
}

【问题讨论】:

  • 为什么?你为什么不做 context.user.where(u=>u.UserId == ID).Select(u=>u.email).FirstOrDefault?
  • @Volodymyr Bilyachat ID 类型是"(1,2,3,4)",所以我不能使用它

标签: entity-framework asp.net-core .net-core asp.net-core-mvc ef-core-3.1


【解决方案1】:

你可以这样做:

public class StringReturn
{
   public string Value { get; set; }
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<StringReturn>().HasNoKey();
}

using (var db = new NorthwindContext())
{
    var result = db.Set<IntReturn>()
      .FromSqlRaw("exec dbo.Scalar")
      .AsEnumerable()
      .First().Value;
    
    Console.WriteLine(result);
}

更多信息请参见我的博文:https://erikej.github.io/efcore/2020/05/26/ef-core-fromsql-scalar.html

【讨论】:

  • 这是解决我问题的好方法之一
【解决方案2】:

好的,首先你的代码中有sql injection。因此,如果用户传入像 1 ) 或 ( 1=1 这样的字段 id 。它会允许它,这在你的情况下基本不是很有害,但是

你真正应该做的是

var ids= HttpContext.Request.Form["ID"].ToString().Split(",", StringSplitOptions.RemoveEmptyEntries).ToList();
if(ids.Any()){
   var Emails = await context.user.Where(u=>ids.Contains(u.UserId)).Select(u=>u.email).ToListAsync();
}

【讨论】:

  • 我认为是第一个,但我对速度性能有要求,我认为我可以搜索所有用户信息,然后使用linq搜索其中一个
  • @Sparkli 我没有理解你所说的性能。在这种情况下,只有第一次会有点慢,但不会成为问题。
  • @Sparkli 我认为你把它复杂化了,给自己制造了问题。保持简单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
相关资源
最近更新 更多