The cast to value type ‘Int32’ failed because the materialized value is null

A linq-to-sql query isn’t executed as code, but rather translated into SQL. Sometimes this is a “leaky abstraction” that yields unexpected behaviour. One such case is null handling, where there can be unexpected nulls in different places. …DefaultIfEmpty(0).Sum(0) can help in this (quite simple) case, where there might be no elements and sql’s SUM returns … Read more

How many Include I can use on ObjectSet in EntityFramework to retain performance?

A query with includes returns a single result set and the number of includes affect how big data set is transfered from the database server to the web server. Example: Suppose we have an entity Customer (Id, Name, Address) and an entity Order (Id, CustomerId, Date). Now we want to query a customer with her … Read more

What’s the difference(s) between .ToList(), .AsEnumerable(), AsQueryable()?

There is a lot to say about this. Let me focus on AsEnumerable and AsQueryable and mention ToList() along the way. What do these methods do? AsEnumerable and AsQueryable cast or convert to IEnumerable or IQueryable, respectively. I say cast or convert with a reason: When the source object already implements the target interface, the … Read more

Like Operator in Entity Framework?

I don’t know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains: where entity.Name.Contains(“xyz”) translates to WHERE Name LIKE ‘%xyz%’ (Use StartsWith and EndsWith for other behaviour.) I’m not entirely sure whether that’s helpful, because I don’t understand what you mean when you say you’re trying to … Read more

LINQ to Entities case sensitive comparison

That’s because you are using LINQ To Entities which is ultimately convert your Lambda expressions into SQL statements. That means the case sensitivity is at the mercy of your SQL Server which by default has SQL_Latin1_General_CP1_CI_AS Collation and that is NOT case sensitive. Using ObjectQuery.ToTraceString to see the generated SQL query that has been actually … Read more

‘Contains()’ workaround using Linq to Entities?

Update: EF ≥ 4 supports Contains directly (Checkout Any), so you don’t need any workaround. public static IQueryable<TEntity> WhereIn<TEntity, TValue> ( this ObjectQuery<TEntity> query, Expression<Func<TEntity, TValue>> selector, IEnumerable<TValue> collection ) { if (selector == null) throw new ArgumentNullException(“selector”); if (collection == null) throw new ArgumentNullException(“collection”); if (!collection.Any()) return query.Where(t => false); ParameterExpression p = selector.Parameters.Single(); … Read more