Querying Entity Framework. Part 24 – Aggregating Nullable Fields

It’s a very simple case for Entity Framework model. I have a nullable column in Clients table.

I want to count values and to sum up them. The LINQ query to EF model can be very simple.

But these queries reveals some magic. Count() returns int type, but Sum() return int?. So you may fall into one of the following cases.

Method Return type Result on all rows Result on not-nullable rows Result on empty dataset
Count() int Count all rows regardless null or not null Count only not-nullable rows Zero
Sum() int? Sum only not-nullable values Sum only not-nullable values Null

The most dangerous is the last case when Sum() returns null, so  you should add a check for null value. If you want to get zero, you need to change a request and add DefaultIfEmpty() method.

Generating Date Sequence With SQL Query

The task is to create SQL query that will produce a date sequence starting from @startDate till @endDate including, i.e. 2017-01-01, 2017-01-02, 2017-01-03 and so on.

There is a couple of obvious solutions.

1. DATEADD() with integer sequence where the integer sequence is an increment

Please take care how many records are in sys.all_objects, it won’t generate a long sequence. If you need more, use a self cross join as shown in Generating Integer Sequence With SQL Query.

2. Recursive query

The last option is very important because SQL Server limits the recursion level to 100 by default.

Casting C# Enums

It’s a short memo how to cast enum to int or string and vice versa.

1. Enum -> int
int value = (int)myEnum;

2. Enum -> string
string name = myEnum.ToString();

3. Int -> Enum
myEnum = (MyEnum)2;

4. String -> Enum
myEnum = (MyEnum) Enum.Parse(typeof(MyEnum), stateName);
bool parseSuccess = Enum.TryParse(stateName, out myEnum);

Querying Entity Framework. Part 23 – Filtering Nullable Field

When you run queries against non-nullable columns (NOT NULL in SQL), everything is going smoothly. You should pay some attention when you deal with nullable fields (one of the cases will be covered at the end of this post).

Now let’s look closer to Entity Framework queries against nullable field. I’ve added a new column LastUpdate with the type DateTime? to my Client entity.

So I have some records with concrete dates, and some with NULL values.

1. Filtering “greater or equal than”

C# understands it perfectly. We have a simple and correct SQL query.

2. Filtering all concrete dates aka WHERE … IS NOT NULL
You can use one of the choices.

Both generate the same correct SQL query.

3. Filtering multiple dates aka WHERE … IN

This case is a bit harder because C# could not compare DateTime[] array and DateTime? field. You need to get a not-nullable value from column.

Looks good, but I’m not satisfied with conversion of C# DateTime array values to SQL Server DateTime2 type. Especially when I set a strong annotation to use Date type in database.

If you don’t want to build a query with every parameter despite whether it is null or not, you might build a dynamic filter like in the following sample.

What will be if both parameters are null? No filters will be added, and you’ll get a query returning all(!) rows regardless of having a concrete value or not. In this case add another check when both parameters are null. One of the simplest implementation is to add third if statement.

Unit Testing C# Async Methods

This time I have a C# async method that should be tested. As you remember, async method must return Task or Task<>.  You can declare an async void method, but this should be used only for event handlers because you have no control on method execution and, the most important, its failure. Beside that, async void method is hard to test.

I have a simple async method that returns Task<int> instead of int in synchronous method (look at my previous post Unit Testing C# Synchronous Methods).

We must be happy that modern unit test frameworks allow to write async unit test where an async method is called asynchronously.

1. Check successful result

The async method being tested is called via await operator. This makes the code being executed in true asynchronous mode.

2.1. Check failure with ThrowsAsync<>

Unit test is awaiting for result from Assert.ThrowsAsync, that is awaiting for result from the method being tested. If you delete the inner async/await, the method would be executed in synchronous mode. If you omit the first outer await, the unit test method might finish before the code in NumberAsync would fail. So you will get wrong results!

2.2. Check failure with Record.ExceptionAsync

Unit Testing C# Synchronous Methods

When you need to unit test a method, you should check happy path (for example, the method returns a resulting value) and sad path (the method throws exception). Here I describe a basic usage of unit testing with Visual Studio 2017 and xUnit version 2.2.

The code being tested:

1. Check successful result (happy path) – it’s very straightforward.

2. Check fail when the method throws an exception (sad path)

If you have faced with MSTest, you might remember [ExpectedException] attribute. In this case MSTest waits for a particular exception would be thrown in a whole unit test method, but not in a specific line of code. Modern unit test frameworks have more graceful capabilities to catch the exception.

2.1. Using Throws<>

But this approach combines Act and Assert phases of unit test in one line of code. Richard Banks suggested a better way in his article Stop Using Assert.Throws in Your BDD Unit Tests.

2.2. Using Record.Exception

At first, I check that the exception was really caught, then check the type of that exception.

Next time I’ll tell about unit testing the asynchronous methods.

Creating GitHub Project In Visual Studio 2017

My goal is to create a new solution and place it in GitHub. This can be done in few steps:

1. Create a GitHub account.
2. Install a GitHub extension for Visual Studio. I’ve downloaded it from https://visualstudio.github.com/
3. Start Visual Studio, open Team Explorer and connect to GitHub.

4. Create a new GitHub repository.

Click link, and enter data in the next form.

5. Switch back to Team Explorer. Click Create a new project or solution link.

6. Choose project type, give it a name. Step forward on wizard steps.

After that you will have the following structure in Visual Studio

and in a disk folder

Now you can write code, commit changes and push them to GitHub.

Converting List To IDataReader

I wrote about using SqlBulkCopy to fast load data from .NET into SQL Server database. This class needs a DataTable or IDataReader instance as a source. You can convert a C# List to DataTable (look here Converting List To DataTable). Now I’ll show a couple of examples how to convert List to IDataReader.

1. Straight implementation of IDataReader interface
I’ve seen a couple of good examples from Bruce Dunwiddie https://www.csvreader.com/posts/GenericListDataReader.cs and Venu Gopal http://technico.qnownow.com/custom-data-reader-to-bulk-copy-data-from-object-collection-to-sql-server/. Based on these two solutions I’ve made my one.

Now you can iterate through IDataReader like you do with SqlDataReader.

2. FastMember NuGet package

Thank you, Marc! it’s a good job https://github.com/mgravell/fast-member

You need to install NuGet package FastMember, add using FastMember; statement, and run this code.

Finding All Controls In ASP.NET Page

When you work with ASP.NET page, you might need to enumerate all controls of a specific type, i.e. text boxes, dropdown list, or table cells. All these controls derive from System.Web.UI.Control class.
To find all controls you need to iterate them recursively from the top one, i.e. Page, or any element that is located on a page (panel, table, etc.). One of the solution is to write an extension method like this.

Also you can use a generic version.

When I need to find all table cells with a specific ID, I can write the following LINQ query:

In C# 6.0 and later you can use Elvis operator in Where clause.

Converting List To DataTable

In my previous post SqlBulkCopy I wrote about how to load data from .NET code into SQL Server database using efficient BULK INSERT command. This class needs a DataTable or IDataReader instance as a source. I’ve collected a couple of examples how to convert List to DataTable.

1. Variation of Marc Gravell solution.
Source: https://stackoverflow.com/a/14548027

2. Solution created by Jennifer Hubbard, Bill Wagner, etc.
Source: How to: Implement CopyToDataTable<T> Where the Generic Type T Is Not a DataRow