Workaround for MySql 5.7 EF DbFirst Issue

Anyone working on .Net application with MySql 5.7 and EF in Db First Approach would have come across what is an officially confirmed bug.  This bug rises when you attempt to generate/update your Entity Model after changes to the Database.

“Unable to generate the model because of the following exception: ‘System.Data.StrongTypingException: The value for column ‘IsPrimaryKey’ in table ‘TableDetails’ is DBNull. —> System.InvalidCastException:”

The workaround you need to do to fix this one

  1. Open your Workbench and execute following commands on your Db.
set global optimizer_switch='derived_merge=off';
set optimizer_switch='derived_merge=off';
  1. Close your workbench ( you might have to restart your visual studio as well ).
  2. Generate/Update your model.
That should work.
Advertisements

Rethrow Exception

CA2200 : Rethrow to preserve stack details. That’s one recommendation that as a developer you might have seen when running Code Analysis on your solution.

So what does it mean ? What does the guilty code looks like and what is the correct way to throw exceptions. Lets start with incorrect code first.

Considering following Code.


    class Program
    {
        static void Main( string[] args)
        {
            try
            {
                new IntermediateClass().IntermediateMethod();
            }
            catch ( Exception Ex)
            {
               
                throw;
            }
        }
    }

    class IntermediateClass
    {
        public void IntermediateMethod()
        {
            try
            {
                new ErrorClass().ErrorMethod();
            }
           catch ( Exception Ex)
           {
                throw  Ex;
            }
        }
    }
    
    class ErrorClass
    {
        public void ErrorMethod()
        {
            int k = 1;
            int j = 3 / --k;
        }
    }
 

We have 3 classes, the main class which invokes a method of IntermediateClass, which in turns invokes method from ErrorClass. The ErrorMethod has been designed purposely to throw an error. It doesn’t implement an exception handling mechanism of its own, and the exception is caught by the Intermediate Class. The Intermediate Class, in turns, throws the exception back to the main class. The Code Analysis Tool has problem with this very same line, where the Intermediate Class throws the exception.

Every Exception Object contains a property called Stack Trace, which carries a list of method call hierarchy starting from the method which threw the exception to the method which caught the exception. If you were to analysis the stack trace of the exception caught in the Main Class, you would find something in similar lines.

“ExceptionHandling.IntermediateClass.IntermediateMethod() in <Path>\IntermediateClass.cs:line 21\r\n at ExceptionHandling. Program. Main (String[] args) in <Path>\Program.cs”

As you can observe, the stack trace doesn’t contains the references to the ErrorMethod, but rather it is reset and traces method starting from the point the exception is rethrown, that is from the intermediate method. In order to preserve the stack information, when you need to rethrow the exception without specifying the exception explicitly. Following would be the modification that would be required in Intermediate Method.


    class IntermediateClass
    {
        public void IntermediateMethod()
        {
            try
            {
                new ErrorClass().ErrorMethod();
            }
           catch ( Exception Ex)
           {
                throw ;
            }
        }
    }

Now if you were to view the stack trace now, the method list would look slightly different.

“ExceptionHandling.ErrorClass.ErrorMethod() in <path>\ErrorClass.cs:line 14\r\n at ExceptionHandling. IntermediateClass. IntermediateMethod() in <path>\IntermediateClass.cs:line 21\r\n at ExceptionHandling.Program.Main(String[] args) in <path>\Program.cs:line “

So next time you rethrow an exception, don’t forget to ensure the exception is not explicitly specified.

Mocking IDispossible with “Using”

Mocking objects is integral part of Unit Testing. The nucleus of Mocking is Dependency Injection, which allows us to inject Mock object into the code. But what happens when programmer has used the “Using” keyword ? For Example,

using(CustomDbCommand cmd = new CustomDbCommand ())
{
// Code
}
<pre>

This makes it difficult to mock DbCommand. The solution lies in deploying Factory Pattern to create our CustomDbCommand. For the purpose, I have created a IDbCommandFactory interface and its concrete solution in DbCommandFactory. It comprises of a method called CreateDbCommandObject, which returns a new instance of CustomDbCommand;

public interface IDbCommandFactory
{
CustomDbCommand CreateDbCommandObject();
}

public class DbCommandFactory : IDbCommandFactory
{
public CustomDbCommand CreateDbCommandObject()
{
return new CustomDbCommand();
}
}

Now that we have our Factory Object ready, it is time to inject it into our Repository Class. I prefer to use Constructor Injection for the purpose.


private readonly IDbCommandFactory objDbCommmandFactory;
public TestRepository( IDbCommandFactory DbCommandFactory)
{
objDbCommmandFactory = DbCommandFactory;
}

public void TestMethod()
{
using ( var cmd = objDbCommmandFactory.CreateDbCommandObject())
{
// Code
}
}

Now we are all set to Mock our CustomDbCommand Object, or in other words, our IDispossible object. Happy Unit Testing.

Composite Primary Key using Data Annotations

When developing domain classes in Entity Framework using Code First Approach, the default code conventions creates a primary key of a property named “ID” or <ClassName>ID. But if you wanted to use another property as your primary key , you can use DataAnnotations and decorate the property using “Key” attribute.

What is more interesting is that you could actually create a composite primary key. All you need to do is use another attribute along with “Key”, namely, “Column”.

image

The above example creates a Table with a Composite Primary Key made up of Dept1 and Dept2. Entity Framework is surely letting the developers live in the comfort zone of Visual Studio rather than dig up SQL Server.

Evil Code 0002 Optional Parameter Vs Method Overloading

Again one of those things which looks so simple, but could drive one mad during debugging.

Much before Optional Parameters came in, C# developers used to depend on Method Overloading for mimicking Optional Parameters. Consider a scenario where both exists, what would be the output ?

Image

The output would be :

Image

The reason behind this is the overload resolution method adopted when we have a overloaded method and a method with optional parameter. Here is what MSDN says.

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

Customized Debugger Tooltip

Code-Execute-Debug-Code-Execute-Debug..

This seems to be never ending cycle for any developer. Considerable amount of time of this cycle is spend in Debug phase, wherein user steps through breakpoints and traverse the objects and their properties.

Thankfully, Microsoft has ensured that primitive types always shows the value, instead of any less-meaningful information.

Image

But what happens when you attempt to hover over instance of a user-defined class ? The pop-up shows the type of class.

Image(1)

Waiting for the pop-up to appear and then using the ‘+’ to traverse the object to see its properties can be a cumbersome task, especially when you are ‘mostly’ interested in one or two properties. Many a times, you would pull you could control what the debugger displays.

This is where DebuggerDisplay  attribute comes into play. Of course, you could always use ‘ToString()’ for the same purpose, but lets say, ‘ToString()’ should be reserved for more meaningful jobs.

All you need to do is to decorate the class with DebuggerDisplay Attribute, pass a string with property name from the class (within curly braces) and you are all set to have debugger tool-tips of your choice.

For example, in my example Class Student, I have different properties like FirstName, LastName, Age among others. But mostly, I am only interested to know the full name of the student while debugging. As you can see from the example below, I have decorated the class with DebuggerDisplay attribute, and passed an expression ( Yes – You heard it right, you can use expression as well) consisting of a combination of FirstName and LastName.

Image(2)

Voila !! That’s at it. Check what happens now when you debug.

Image(3)

Simple, but interesting isn’t it ?.