给我对象引用未设置为对象的实例。何时将linqtoentites投射到linqtoobjects?

时间:2014-07-31 17:13:00

标签: c# asp.net-mvc linq

这就是我所做的:

我的班级

public class Order
{
  // remove some code for brevity
  public virtual Foo Foo { get; set; }
  public virtual Bar Bar { get; set; }
  public virtual ICollection<Knife> Knives { get; set; }
}

查看模型

更新

public class OrderVm
{
  public string SomeText { get; set; }
}

在我的控制器中

第一次尝试:这给了我Object reference not set to an instance of an object.

var tmp = _db.Orders
           .Include("Foo")
           .Include("Bar")
           .Include("Knives")
           .AsEnumerable()
           .Select(o => new OrderVm
           {
             SomeText = o.Knives.Count().ToString() + " some text here"
           });

第二次尝试:给我错误LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

var tmp = _db.Orders
            .Include("Foo")
            .Include("Bar")
            .Include("Knives")
            .Select(o => new OrderVm
            {
              SomeText = o.Knives.Count().ToString() + " some text here"
            });

基本上,我需要的是在分配属性时需要执行.ToString()(需要从int转换为字符串)。他们说,通过调用LinqToEntities(建议显示而不是LinqToObjects)将AsEnumerable()转换为ToList()但是当我尝试投射它时。它让我Object reference not set to an instance of an object.真的不知道为什么。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

第二个片段不是在C#代码中执行投影,它将该代码转换为在数据库端执行的SQL代码。您正在执行的操作的SQL等价物可以在null值上执行,并且只会传播null而不是使查询崩溃。

第一个查询使用C#操作和空值处理行为执行C#应用程序中的代码,即在尝试调用null值上的函数而不是传播null时抛出异常。 / p>

如果您可以在数据库端执行投影,则可能应该这样做,因为这样可以防止您不必要地将不需要的信息传递给应用程序。如果您在C#端执行投影,则需要对其进行编码,以便它可以正确处理null值而不会崩溃。