【问题标题】:Convert to int inside LINQ statement possible?可以在 LINQ 语句中转换为 int 吗?
【发布时间】:2013-08-26 21:30:35
【问题描述】:

我想使用简单的 LINQ 语句将记录保存在数据库中。我发现不可能在 linq 语句中使用Convert.ToInt32,如下所示:

using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = Convert.ToInt32(formId);
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

我当然可以在 LINQ 语句之前进行转换,很想知道这是否是我唯一的选择。

【问题讨论】:

标签: c# linq-to-entities


【解决方案1】:

在您使用 using 语句之前,我会 Convert.ToInt32(formId)。

Linq 不喜欢依赖于 ORM 的 Convert 语句

看看这个 Problem with converting int to string in Linq to entities

【讨论】:

  • 仔细阅读问题:“我当然可以在 LINQ 语句之前进行转换,很想知道这是否是我唯一的选择。”
【解决方案2】:

您是否尝试过使用 int.Parse() 或 int.TryParse()?另外,为什么不能使用 Convert.ToInt32()?你有什么错误吗?

【讨论】:

  • 不,Convert.ToInt32() 可以使用 OK。他只是想知道是否有其他方法可以做到这一点。如果formId 是字符串,int.Parse 也会这样做。
  • 好的。无论如何, Convert.ToInt32() 仅适用于 32 位整数。我认为他应该尝试使用 int.Parse() 或 int.TryParse() 进行更安全的转换。
  • 我们还有Convert.ToInt64()int.Parse实际上是Int32.Parse
  • @Siva、int.Parseint.TryParse 仅适用于“32 位 int”
【解决方案3】:

您可以像这样转换变量: (int)formid

您必须检查“formId”是否可以转换为 int。

using (var context = new Stc.LeadTracker.DataModel.Models.DBNameContext())
{
    var newLead = new DataModel.Models.LeadRequest();
    newLead.FormId = (int)formId;
    newLead.Request = queryString;
    newLead.Success = true;
    newLead.RetryCount = 0;
    newLead.CreatedBy = nvCollection["iw"];
    newLead.CreatedDateTime = DateTime.Now;
    context.LeadRequests.Add(newLead);
    context.SaveChanges();
    leadId = newLead.LeadRequestId;
}

这里有一个类似的问题: LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression

【讨论】:

    猜你喜欢
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多