Posts Tagged ‘VB.NET’

Linq to SQL Query gives an InvalidOperationException with message “Cannot compare entities associated with different tables.”

Wednesday, September 15th, 2010

If you try to do a Linq to SQL query and it runs fine, but gives you an exception of type InvalidOperationException and the message is “Cannot compare entities associated with different tables.” then it probably means that you are trying to pass in an object of one type and compare it to another type.  I suspect that you will probably only get this error if Linq attempts to translate the error to SQL – if you run it in memory, you might not get an error at all, as it may just do a straight object comparison and conclude that they are different objects.

An example would be something like


Dim p = DBContext.People.First
Dim q = From a in DBContext.Addresses Where a Is p
Dim addr = q.First

The final line will result in this exception as Linq to SQL is attempting to translate the query into SQL and it (correctly) can’t find any way of writing a query that compares a person to an address!

Exceptions Explained: NullReferenceException

Sunday, November 8th, 2009

This is the first on a new series of posts that I’m going to be doing on explaining various different exceptions, what they mean, when you might get them and how to avoid them.

The first one is the NullReferenceException, which usually comes with the message “Object reference not set to an instance of an object.”. This Exception occurs when you try to access an object reference which is set to Nothing.

First of all, you need to understand the difference between value types and reference types in .NET. With a value type, we only care about what data is stored within it. With a reference type, the actual instance of the type is important in itself. For example, we may have an Integer, which contains 10. Integers are value types, and there is generally nothing particularly different between one number 10 and another number 10 if they are both Integers, so they are effectively identical.

Reference types on the other hand are different. If we have two customers, and both of them happen to be called “John Smith”, we don’t want to treat them as being the same thing just because they have the same name. The other difference with reference types is that we can have an empty reference – Nothing (or null in c#).

In fact, behind the scenes, reference types store a location in memory of the instance. In older programming languages, such as C/C++, these were known as pointers, and you could actually access them just like a number and change the item that they were pointing to with arithmetic operators (+/-/increment/decrement etc.) This created a number of potential problems and so references were created to protect pointers from causing too much damage. References also the garbage collector to keep track of what is referencing an object instance so that the instance can be cleared up when it is no longer in use.

The NullReferenceException is thrown when you attempt to access an object reference which is set to Nothing. This can easily happen because as mentioned above, all variables of a reference type will be initialised to Nothing by the .NET framework if they have not been explicity set to something else.

For example,

        Dim c As Customer
        c.Name = "John Smith"

The second line in the above piece of code will throw a NullReferenceException as the variable c is still set to Nothing, and when the .NET framework attempts to access the Name field, it will find that the object does not exist.

This is easily resolved by setting c to whatever Customer you wish to use, or to a New Customer.

IsNot Operator in VB.NET

Friday, July 3rd, 2009

Somehow I seem to have missed Microsoft adding in the IsNot operator into VB.NET.  I’ve just found it now.  It will make things a lot easier to read and write.  The number of times that I write If Not a Is b Then …  it should save me a lot of annoyance to write If a IsNot b Then …I’ve tried “Is Not” in the past with a space, but that doesn’t work.

CType and DirectCast

Friday, July 3rd, 2009

VB.NET supports 2 different keywords which are related to casting.

DirectCast takes the object which is passed in and assumes it to be of the casted type or an inherited type.  This means that if you try to DirectCast an Integer to a Single, it won’t work.  If the compiler can see that it won’t work because it isn’t an inherited type, you’ll get a compiler error.  If you try it on a variable in eg. an Object at runtime, you’ll get an InvalidCastException.

The alternative is to use CType, which is much cleverer and will try to find a way to convert from one type to another.  This means that you can Ctype(“2.334″, Single) and it will parse the string and give you a Single length floating point number.  It will also check for overloading of the CType operator to see if it can convert using that.  This makes it very powerful, although it does come with the cost of a lot more processor usage.  However, for most modern applications, unless you are doing something heavily time constrained with a large amount of iterations in a  loop, it is unlikely to be an issue.

With Slows Down Code?

Tuesday, June 30th, 2009

I just remembered something that happened a few years back in .NET 1.1 days (or maybe even it was .NET 1.0).

We were writing a rather complicated piece of code that needed to do lots of loops processing objects. Since it was taking an extremely long time, we ran it through a code profiler (a nice thing called ANTS Profiler – made by a company called Red Gate). One of the things that the profiler highlighted was that when we were using a With block to access a the return value of a function, every time the runtime used the With block to access the value, it was calling the function and taking extra time! This was a little surprising, as we had thought that With was dealt with at compile time, but apparently not. If my memory serves me correctly, I think that it was still slow when we assigned the return value of the function to a variable and used With to access that.

The basic upshot is that if you are in a situation where you are really bothered about speed, don’t use With to write code like that.

Linq Part 3 – Query Format

Monday, June 29th, 2009
This entry is part of a series, Linq»

It is very easy when you are familiar with SQL to constrain yourself to treating Linq queries in a similar fashion and not take advantage of some of the new features that Linq allows. Of course, Linq does impose its own constraints, as does each Linq provider, so it isn’t always easier.

It is definitely worth getting your head around the fact that in Linq, you can query a query.  With some providers, this might mean that you are querying the results of a query, but with others, it can mean that you are simply building another query, which will only actually be executed when you try to retrieve the results.

For example,

Dim q = From p in DataContext.People Where p.Surname=”Smith”

q = From p in q Where p.FirstName=”John”

In Linq to SQL, this is perfectly efficient as it will only run SELECT * FROM Person WHERE Surname=’Smith’ AND FirstName=’John’ or something similar.

Equally, you can also combine multiple queries into a single statement, such as…

Dim q = From p in DataContext.People Select p.ID, p.Surname Order By p.Surname Select ID

…and of course you don’t need to worry about the order of the statements – notice a Select can come after an Order By!  The thing to remember is that each Select/Group effectively creates a different context (as in a variable context), so you have different variables available at each point in the query.

Linq Part 2 – From

Wednesday, June 24th, 2009
This entry is part of a series, Linq»

A Linq query will always start with From item in datasource

When I initially started using Linq, I thought that was a little odd, and why didn’t Microsoft just use SQL style Select columns from datasource.  I thought about this for a minute, and realised that the problem with that is that you can’t use Intellisense to get the column names because you don’t actually know what they are until you’ve specified the data source.

Another reason for this is that the Select part of a Linq query is not compulsory, so it makes more sense to start with the part that is.

You might find it a little confusing having to specify item if you are thinking in SQL terms, as you would usually just include a table name and possibly an alias in SQL.  The point in item is that a Linq query is a bit like a For loop in a single statement.  You are effectively looping around the items in the data source.  An individual provider might not actually implement it that way (Linq to SQL doesn’t – if you use a Where clause, it is translated to SQL instead of retrieving all the data and checking what matches), but that is the abstraction that we are using.  We don’t reference the item by using the datasource name because we might still want to access something else in the datasource separately in the query.

More details on installing .NET 3.5 in Windows 2000

Wednesday, April 22nd, 2009

I’ve had a comment that my previous post explaining how to install .NET 3.5 in Windows 2000 wasn’t very clear, so I’ll try to clarify it a little…

First of all, let me explain how it works.  .NET is actualy 2 separate things.  There is the .NET runtime, which deals with interpreting the MSIL intermediate code and executing it.  There is also the .NET Framework, which are all the libraries containing the classes that you usually code with in .NET.

In theory, the .NET runtime can be used without the .NET framework (although you’d probably need a couple of DLLs to define things like the basic types).  You could use an entirely different framework which sits on top of the same runtime and is compiled to MSIL.  I’m not aware of any that exist though.

The really interesting bit is that there are actually only 3 versions of the .NET runtime – 1.0, 1.1 and 2.0.  1.0 and 1.1 are used for the corresponding framework versions, but 2.0 is used for running framework 2.0, 3.0 and 3.5.  

In fact, in terms of the framework, 3.0 is 2.0 plus some extra stuff, and 3.5 is 3.0 plus extra stuff.  The trick which I rely on is that you can install 2.0 in Windows 2000 and just add the extra stuff that you need. 

For my purposes, all I needed was support for Linq and Linq to SQL and a few other bits and bobs.  All this is available in .NET Assembly DLL files.  you just need to make sure that the assemblies are available to be loaded by the application you are running.  

You also need to make sure that you have any prerequisites for those assemblies, because a lot of them will access classes in other assemblies.  There are 2 ways of dealing with that.  You can either copy in the entire set of DLLs, or you can keep running your program and looking to see what assembly it can’t find when it throws an exception, copying that DLL in and re-running it until you don’t get any more exceptions.

There are 2 ways of making the assemblies available to your program.  You can either register them in the GAC so that they can be accessed from anywhere (I’ve not tried this and I probably wouldn’t recommend it – if you want to know how to do this, google installing an assembly in the GAC), or you can just copy them into the application folder that your EXE sits in (or bin folder on your ASP.NET website will probably work too).  This does make for a lot of files in that folder, but it works!

You should be able to find the .NET 3.5 assemblies in a folder on a PC that has .NET 3.5 installed under

Program Files\Reference Assemblies\Microsoft\Framework\v3.5 

nb. Make sure that you have Windows 2000 SP4 and .NET framework 2.0 SP1 installed on the Windows 2000 PC!  You might also need to install KB 835732 before .NET 2.0 SP1.

Linq Part 1 – What is Linq?

Tuesday, March 24th, 2009
This entry is part of a series, Linq»

Linq is an abbreviation for Language Integrated Query.  The idea of it is that you can write a query on a source of data inline as part of your code.  It is particularly clever because Linq allows different providers to be used so that different types of data can be queried.  There are Linq providers that are part of the .NET Framework for querying anything based on IEnumerable (including Lists, Collections, Arrays, etc.), XML, SQL Server databases (using Linq to SQL). 

There are also providers available for querying Oracle, MySQL, various webservices (one of the earliest ones I came across was Linq to Amazon).  It is a very powerful system with lots of flexibility.

Another point about Linq is that you can build queries on top of queries and depending on the provider, it only compiles and executes the final query when you try to access the data.  For example, you could do a query like

Dim people = From p in DB.People Where p.FirstName=”John”

people = From p in people Where p.Surname=”Smith”

Once you try to access people, (eg. by looping through it), Linq will execute an SQL query something like

SELECT [ID], [FirstName], [Surname] FROM [Person] WHERE [Person].[FirstName]=’John’ AND [Person].[Surname]=’Smith’

.NET 3.5 SP1 in Windows 2000

Monday, March 23rd, 2009

I’ve posted a couple of times earlier on .NET 3.5 in Windows 2000.  The .NET framework 3.5 sits on .NET 2.0 SP2, which is only available to install on Windows XP and onwards.  However, from experimentation, this does not mean that the same tricks don’t work.  As long as you have .NET 2.0 SP1 installed, you can get away with copying most of the DLLs in with no trouble.  It also seems to work with some of the newer ones.