LINQ的VAR和类型的对象 [英] Linq VAR and Typed Object

查看:207
本文介绍了LINQ的VAR和类型的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想code的样本。
目前我使用LINQ在C#和asp.net 4 EF4

I would like a sample of code. At the moment I use linq in c# and asp.net 4 ef4

       var querySlotOrder = from slot in context.CmsSlots
                             where slot.SlotId == myCurrentSlotId
                             select slot;

           if (querySlotOrder.SlotOrder == myNewSlotOrder)
                e.Cancel = true;

这LINQ查询只返回一个记录。

This linq query return only a record.

使用VAR我不能得到的类型的对象,我无法访问其属性SlotOrder。

Using VAR I cannot get the Typed Object and I cannot access its property SlotOrder.

如何更改查询?感谢您的帮助。

How to change the query? thanks for your help

。有用的主题资源:

http://msdn.microsoft.com/en-us/library/ bb384065.aspx

http://msdn.microsoft.com/en-us/library/ bb397947.aspx

http://msdn.microsoft.com/en-us/library/ bb397678.aspx

推荐答案

即使你的查询返回一个对象,在选择方法,它使用的是幕后,其实不然。它返回一个的IQueryable< T> 在EF

Even if your query returns a single object, the Select method, which you are using behind the scenes, doesn't. It returns an IQueryable<T> in EF.

您应该使用的方法,如的SingleOrDefault 首页 FirstOrDefault 如果你要存储一个对象。

You should use a method such as Single, SingleOrDefault, First, FirstOrDefault if you want to store a single object.

var querySlotOrder = (from slot in context.CmsSlots
                      where slot.SlotId == myCurrentSlotId
                      select slot).Single();

四种方法之间的区别是:

The difference between the four methods is:


  • :返回序列的唯一元素,如果序列中只有一个元素不是抛出一个异常

  • 的SingleOrDefault :返回序列,或者如果序列为空,默认值的唯一元素;如果序列中的多个元素,此方法将引发异常。

  • 首先:返回序列的第一个元素

  • FirstOrDefault :如果序列不包含任何元素返回序列的第一个元素,或默认值

  • Single: Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
  • SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
  • First: Returns the first element of a sequence.
  • FirstOrDefault: Returns the first element of a sequence, or a default value if the sequence contains no elements.

(从 MSDN 定义)

这篇关于LINQ的VAR和类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆