score:7
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.
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:
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.
(Definitions from MSDN)
score:-3
Why do you use a var
? if you know the type of the object you expect you should type querySlotOrder
:
MyObjectType querySlotOrder = (from slot in context.CmsSlots
where slot.SlotId == myCurrentSlotId
select slot).FirstOrDefault();
if (querySlotOrder.SlotOrder == myNewSlotOrder)
e.Cancel = true;
score:0
This is madd0's code but reformated to use C# style instead of SQL style
var querySlotOrder = context.CmsSlots
.Where(slot => slot.SlotId == myCurrentSlotId)
.Single();
it's better to read and understand whan SQL style
score:2
As Dennis is pointing out in his answer, you're not getting an instance of one object, you're getting an IEnumerable back from your query. In order to access the SlotOrder property you need to pick a particular item from the collection, most likely the first - judging by your query.
score:3
The linq query returns not a record, but a collection of records that has only 1 element. If you want to get the first element and if you are sure that there is only 1 element in the collection, use Single extension method:
var querySlotOrders = from slot in context.CmsSlots
where slot.SlotId == myCurrentSlotId
select slot;
var querySlotOrder = querySlotOrders.Single();
if (querySlotOrder.SlotOrder == myNewSlotOrder)
e.Cancel = true;
score:5
The LINQ select
-statement always returns a queryable collection. Therefore you need to fetch a single object from it.
var querySlotOrder = (from slot in context.CmsSlots
where slot.SlotId == myCurrentSlotId
select slot).FirstOrDefault();
score:5
The type of the returned object is IQueryable<CmdSlot>
(assuming that CmdSlot
is the type of the elements), and querySlotOrder
gets that type (that's the effect of var
; var
itself is not a type). If you are absolutely sure that there will always be exactly one element in the result collection, you can retrieve it with querySlotOrder.Single()
.
Source: stackoverflow.com
Related Query
- Linq VAR and Typed Object
- Finding the maximum valued and different typed items in an object list by using Linq
- LINQ to SQL: GroupBy() and Max() to get the object with latest date
- Iterate through properties and values of an object returned via a linq query on a domain model
- Differences between IEquatable<T>, IEqualityComparer<T>, and overriding .Equals() when using LINQ on a custom object collection?
- I am wondering about the state of connection and impact on code performance by 'yield' while iterating over data reader object
- LINQ Except operator and object equality
- Using LINQ to do some calculations on the current and the next object
- Enumerable.Empty<T>().AsQueryable(); This method supports the LINQ to Entities infrastructure and is not intended to be used directly from your code
- How can I use LINQ to project this parent and children object model into a flat, single object?
- Linq projection of flattened table into parent and child object graph
- LINQ Source Code Available
- Linq with where clause in many-to-many EF Code First object
- Refactor Linq code and "LINQ to Entities does not recognize the method"
- LinQ to objects GroupBy() by object and Sum() by amount
- How can I code an outer join using LINQ and EF6?
- Convert Datatable to Object with Linq and Group by
- How to use Linq to select and group complex child object from a parents list
- Troubles with LINQ and object references
- linq object equality and how to properly override it
- C# - Linq optimize code with List and Where clause
- IEqualityComparer and Linq Distinct - Hard Code GetHashCode()
- creating Linq to sqlite dbml from DbLinq source code
- Stubbing Code for Test With Linq Expressions and Lambdas
- What is the best way to get the percentage for an object in linq list and map it to JSON?
- LINQ All and Any complex object
- Linq to sql as object data source - designer problem with partial classes
- Linq and var keyword
- Get minimum and maximum time value from list of object property using Linq
- How to use OrderBy Linq when object is null and property is integer
More Query from same tag
- Is it possible to replace this foreach loop with Linq?
- Get count of object from list?
- Getting duplicate data based on dynamic key
- Comparing elements in an IEnumerable to eachother
- How to reference a specific object from a list in a config file using .NET MVC with C#
- Query MongoDb from C# - using Linq .Any() with predicate
- How|Where are closed-over variables stored?
- IEnumerable array disappeared in Visual C#
- Use Count in Linq returns different results than SQL query
- Sort the list of strings after string data was added to the list and add method returns void
- Are Linq's Skip and Take optimized for arrays? [4.0 edition]
- How can I insert an XElement into an existing xml-file?
- C# - Getting flat many-to-many List of Objects into List of distinct combinations of two Lists of objects
- error in Linq query
- How to embed dynamic OR condition after WHERE statement in linq query c#
- Is it possible to alter a DataServiceQuery after it has been constructed?
- Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<int, x>>' to 'System.Collections.Generic.List<x>'
- Sql ExecuteSqlCommand to LINQ
- How to get specific column in Entity Framework
- Distinct() not working, behaving differently in .NET 5 and 4.7.2
- How to convert linq query into a list keyvaluepair
- Linq how to select only a small subset of a large result set?
- Linq command to group by date - how to group
- how to get data from a list inside a list in a class : where T:class
- Building a custom|progressive query in LINQ?
- C# Linq Sum query on IDictionary
- How can I make a more efficient Entity Framework LINQ call than a nested loop
- Why is linq result updated, if a source is updated afterwards?
- Unit testing collection contents meet certain criteria using lambdas/LINQ
- LINQ to Entities is pluralizing table names actually executed in SQL Server. How can I avoid it?