Friday, September 30, 2016

ASP.Net Migration Error

I did a lot of updates on my project and since I use Entity Framework Code First, I depend on migration commands. This time, my Visual Studio suddenly does not recognize the commands. I have the following error message when attempting to enable migration:

The term 'Enable-Migrations' is not recognized as the name of a cmdlet, function, script file, or operable program


Some people say to reinstall entity framework with the following command:

Install-Package EntityFramework -IncludePrerelease

But it didn't work for me since I have it installed, so I find a way to force reinstall the package which works! The command as follow:

Update-Package -reinstall EntityFramework -IncludePrerelease

Tuesday, September 27, 2016

Deleted Data Row and LINQ

Another interesting programming problem. I have the following code in VB.Net which throws error:

dataRow.Delete() 'One of the rows in dataSet

dataSet.Tables("TableName").Rows.Cast(Of DataRow).FirstOrDefault(Function(dr) dr("ColumnName") = certainCondition)

Problem

The error says "Deleted row information cannot be accessed through the row". Pretty clear message, so I did the following:

dataSet.Tables("TableName").Rows.Cast(Of DataRow).FirstOrDefault(Function(dr) dr("ColumnName") = certainCondition AndAlso dr.RowState <> DataRowState.Deleted)

Solution

But the code above throws the same error. Apparently the deleted check has to be the first condition which again makes sense. Thus, the following code runs perfectly fine:

dataSet.Tables("TableName").Rows.Cast(Of DataRow).FirstOrDefault(Function(dr) dr.RowState <> DataRowState.Deleted AndAlso dr("ColumnName") = certainCondition)

There you go.

If Operator and Nothing on VB.Net

I encountered an interesting thing recently in my programming experience. I have the following method:
Private Sub SomeMethod(parameter As Nullable(Of Double))
   If parameter.HasValue Then
      'Do something
   Else
      'Do something else
   End If
End Sub

Problem

To call it, I use the following:
SomeMethod(If(someObject.IsTrue, Nothing, someDouble))
However, it didn't work as I expect it to be. The one that confused me is, the HasValue always returns true although Nothing is being passed to the method. 

Solution

It took me awhile to realize that the If operator in this case will return the same type for both results (true and if false). And in VB.Net, Nothing equals default value which for Double is 0.0 while I want Nothing to act as Null. Thus to fix the issue, I have to rewrite it as:

If someObject.IsTrue Then
   SomeMethod(Nothing)
Else
   SomeMethod(someDouble)
End If