Linq var and typed object

I need some sample code. I am currently using 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;

This linq query returns only a record.

Using VAR I cannot get a Typed object, and I cannot access its SlotOrder property.

How to change the request? thanks for the help

Use a resource on the topic:

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

+3
source share
7 answers

Even if your query returns a single object, the method Selectyou use behind the scenes does not work. It returns IQueryable<T>to EF.

, Single, SingleOrDefault, First, FirstOrDefault, .

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

:

  • Single: , .
  • SingleOrDefault: , ; , .
  • First: .
  • FirstOrDefault: , .

( MSDN)

+7

LINQ select -statement . .

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

: IQueryable<CmdSlot> (, CmdSlot - ), querySlotOrder ( var; var ). , , querySlotOrder.Single().

+5

linq , , 1 . , , 1 , Single extension:

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

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

As Dennis points out in his answer, you are not getting an instance of one object, you are getting IEnumerable back from your request. To access the SlotOrder property, you need to select a specific item from the collection, most likely the first - judging by your request.

+2
source

This is madd0 code, but reformatted to use C # style instead of SQL style

var querySlotOrder = context.CmsSlots
  .Where(slot => slot.SlotId == myCurrentSlotId)
  .Single();

better read and understand SQL style

0
source

Why are you using var? if you know the type of object you expect, you should enter querySlotOrder:

MyObjectType querySlotOrder = (from slot in context.CmsSlots
                             where slot.SlotId == myCurrentSlotId
                             select slot).FirstOrDefault();

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

Source: https://habr.com/ru/post/1796052/


All Articles