【问题标题】:Value cannot be null error in asp.netasp.net中的值不能为空错误
【发布时间】:2017-07-13 14:17:20
【问题描述】:

我想知道为什么它在我下面的代码中返回一个空值:

using (var context = new MusicStoreDBEntities())
{
    var bay = (from g in context.stringInstrumentItems
               where g.brand.name == name.Text select g)
               .FirstOrDefault();
    context.stringInstrumentItems.Remove(bay);
    context.SaveChanges();
}

var 托架返回 null。我做错了什么?这是我试图将其转换为实体框架的等效原始 sql 查询:

string queryGuitarItems = "DELETE S FROM stringInstrumentItem S JOIN brand B ON S.brandId = B.brandId WHERE B.name = @brand";
using (SqlConnection connectionGuitarItems = new SqlConnection(ConfigurationManager.ConnectionStrings["musicStoreConnection"].ToString()))
{
    using (SqlCommand commandGuitarItems = new SqlCommand(queryGuitarItems, connectionGuitarItems))
    {
        connectionGuitarItems.Open();
        commandGuitarItems.Connection = connectionGuitarItems;
        commandGuitarItems.Parameters.Add(new SqlParameter("@brand", name.Text));
        commandGuitarItems.ExecuteNonQuery();

        connectionGuitarItems.Close();
        commandGuitarItems.Parameters.Clear();

    }
}

让我知道这两个查询是否相似。我真的在尝试将所有原始 sql 查询更改为实体框架,这是一个开始。

【问题讨论】:

  • 运行 sql-profiler 并查看广告生成的 sql-code
  • FirstOrDefault() 如果没有找到符合您条件的内容,则返回 null,您确定您的数据库中有匹配项吗?
  • 那个 SQL 命令会愉快地“删除” 0 条记录。当找不到匹配项时,您的 FirstOrDefault() 可能会返回 null。所以检查那个空值。

标签: c# sql asp.net database entity-framework


【解决方案1】:

您尚未在 linq 查询中包含您的联接。由于您没有包含Brand,因此它不会根据您的where 子句获取任何记录。

由于您使用的是实体框架,因此您可以尝试以下操作:

using System.Data.Entities;

using (var context = new MusicStoreDBEntities())
{
    var bay = context.stringInstrumentItems.Include(i => i.brand)
        .FirstOrDefault(x => x.brand.name == name.Text);

    if (bay != null)
    {
        context.stringInstrumentItems.Remove(bay);
        context.SaveChanges();
    }
}

.Include() 从数据库中获取相关的 brand 记录,就像 JOIN 在 SQL 代码中所做的一样,因此您现在应该有一条记录。

排除它的问题与连接的任何一侧都没有匹配的记录相同 - 查询不会选择任何记录。

【讨论】:

  • 作为一个实验,在Remove 行放置一个断点并检查元素。鉴于您的 linq 查询作为选择,我敢打赌 g.brand 为空或为空
  • 您的解决方案在这部分给了我一个错误:(i => i.brand) .. 它说无法将 lambda 表达式转换为类型“字符串”,因为它不是委托类型
  • 您是否为 System.Data.Entities 添加了using?如果您使用的是 Entity Framework 6,它应该可以正常工作。否则,将该 lambda 表达式替换为 "brand" 以定位链接实体
  • 是的,我几秒钟前才弄明白。
猜你喜欢
  • 2015-11-07
  • 1970-01-01
  • 2014-01-30
  • 2017-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 2020-09-25
相关资源
最近更新 更多