Saturday, September 19, 2009

casting nullable ints or int?

Hmm, love nullable types :) But sometimes they can be a little tricky. When working with Linq, you sometimes create anonymous types as a return. If the field that you bring back is a nullable column in the database, it can mean that the anonymous type created is a nullable type as well. The next computation you use can check to see if the value is null, and if it's not, assign it to a new variable. Not saying this is the best way or even the only way, but it worked for me, and I liked it :)

int value = (myNullableValue.HasValue) ? 0 : myNullableValue.Value;

What does it all mean? It's a ternary operation.

If the first value is true ((myNullableValue.HasValue) ? 0), return that, otherwise return the second expression (myNullableValue.Value)

Otherwise if you've already done a nullable check ...
int value = (int)myNullableValue;

Friday, September 18, 2009

Dynamic data website error

If you get this error when setting up a dynamic website there are two things it could be:

"There are no accessible tables. Make sure that at least one data model is registered in Global.asax and scaffolding is enabled or implement custom pages"

Firstly check  the Global.ascx.cs page to make sure that you've updated YourDataContext to whatever the name of your datacontext is.

Secondly make sure ScaffoldAllTable is set to True.

model.RegisterContext(typeof(YourDataContext), new ContextConfiguration() { ScaffoldAllTables = true });