Tuesday, February 9, 2016

Entity Framework - IDbSetExtensions.AddOrUpdate and Explicit Foreign Keys

When you are seeding the instance data in Entity Framework, you might see the following error when you are doing AddOrUpdate on an Entity which has explicit Foreign Keys defined.

The UPDATE statement conflicted with the FOREIGN KEY constraint "FK_something". The conflict occurred in database "database_name", table "table_name", column 'column'. The statement has been terminated.

For instance let’s take the following scenario.
public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual List<Employee> Employees { get; set; }
}
 
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Department Department { get; set; }
}
 
public class MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<Department> Departments { get; set; }
}
 
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
 
    protected override void Seed(MyDbContext context)
    {
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 1,
            Name = "Microsoft Visual Studio"
        });
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 2,
            Name = "Microsoft SQL Server"
        });
        context.SaveChanges();
 
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 1,
            Name = "Jaliya Udagedara",
            Department = context.Departments.First(d => d.Name == "Microsoft Visual Studio")
        });
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 2,
            Name = "John Smith",
            Department = context.Departments.First(d => d.Name == "Microsoft SQL Server")
        });
        context.SaveChanges();
    }
}
Here I have Employee and Department Entities where Employee belongs to a Department. A foreign key will be created by EF on Employee towards Department. I am seeding up some instance data using IDbSetExtensions.AddOrUpdate and I can run Update-Database without any issues.

But now, let’s changed the Employee entity as follows. Here I have explicitly defined a Foreign Key using data annotations (you can do it using Fluent API as well).
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Department_Id { get; set; }
    [ForeignKey("Department_Id")]
    public virtual Department Department { get; set; }
}
Now after adding a new migration and if I try to run Update-Database, I will be getting the mentioned error.

image_thumb3
Error
At first you might find this bit surprising. Now let’s see what is happening here. I have attached a debugger for the Seed to make it much easy to understand.

image_thumb7
Debugging
From the Seed method, we were setting Department property of Employee which was working fine. But now after explicitly defining Foreign Keys, as you can see it’s not getting set even though we are setting it. The reason is now the relationship is working through Department_Id property. And since we are not setting a value to Department_Id, it is 0, and that’s the reason behind the error we were getting. So to fix this, we will have to set the value for Department_Id property and not to the Department property.
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }
 
    protected override void Seed(MyDbContext context)
    {
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 1,
            Name = "Microsoft Visual Studio"
        });
        context.Departments.AddOrUpdate(d => d.Name, new Department()
        {
            Id = 2,
            Name = "Microsoft SQL Server"
        });
        context.SaveChanges();
 
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 1,
            Name = "Jaliya Udagedara",
            Department_Id = context.Departments.First(d => d.Name == "Microsoft Visual Studio").Id
        });
        context.Employees.AddOrUpdate(e => e.Id, new Employee()
        {
            Id = 2,
            Name = "John Smith",
            Department_Id = context.Departments.First(d => d.Name == "Microsoft SQL Server").Id
        });
        context.SaveChanges();
    }
}
Now you can run Update-Database command without any errors.

image_thumb12
Update-Database Succeeded
I am uploading the sample code to OneDrive, so you can try it yourself.

Happy Coding.

Regards,
Jaliya

Monday, February 8, 2016

Debugging Seed method in Entity Framework

This is a quick post on how you can debug the Seed method. When you run Update-Database, the seed will be running silently and there are sometimes that we need to debug it.

Just insert the following code snippet to the Seed method.
if (System.Diagnostics.Debugger.IsAttached == false)
{
    System.Diagnostics.Debugger.Launch();
}
Happy Coding.

Regards,
Jaliya

Wednesday, February 3, 2016

How to Keep DateTime Unchanged when JSON is Parsed through Web API

You might have experienced this where when you send a DateTime object to Web API with the Time Offset, Web API is doing the math and calculating the UTC DateTime using the Offset itself.

If I give an example, this is how my client side code sends the DateTime object to Web API.

image
DateTime in Client Side
And from the Web API, this is what I am getting.
image
DateTime in Server Side
So as you can see here, the Web API’s JSON formatter has converted the passed DateTime to UTC time using the given Offset.

Sometimes this is not the expectation and we want to pass the DateTime as it is. Now let’s see how we can achieve it by simple changing the Web API JSON formatter settings.
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
        {
            DateTimeZoneHandling = DateTimeZoneHandling.Local
        };
 
        // other api configuration
    }
}
Now if I send the data back again, I am getting the DateTime as it it without converting it to UTC time.
image
DateTime in Server Side
Happy Coding.

Regards,
Jaliya

Monday, January 25, 2016

Enabling Cross Origin Resource Sharing (CORS) in ASP.NET Web API 2

This is a quick post on how to enable CORS in Web API 2. It’s actually fairly an easy task. First you need to install Microsoft.AspNet.WebApi.Cors nuget package to the Web API project. You can do it from either of following ways.

1. Nuget Packet Manager
image
Nuget Packet Manager
2. Package Manager Console
Install-Package Microsoft.AspNet.WebApi.Cors
Then modify the Register method in WebApiConfig.cs as follows.
public static void Register(HttpConfiguration config)
{
   // enabling cross-origin requests
   config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
 
   // other configuration
}
Make sure to add using System.Web.Http.Cors. You can customize the policy by setting different values to EnableCorsAttribute properties.

Happy Coding.

Regards,
Jaliya

Friday, January 22, 2016

Visual C# Technical Guru - December 2015

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - December 2015
Happy Coding.

Regards,
Jaliya

Friday, January 8, 2016

Using .NET Core with “dotnet” CLI

In this post let’s see how we can create a simple “Hello World” console application which targets .NET Core with the newly introduced “dotnet” Command Line Interface.

First what you need to do is install .NET Core to your machine. The easiest way to do is by running the following MSI installer.

After the installation, create a folder and open up a command prompt there (shift+right click on the folder and you can select Open command window here)
image
Open command window here
On the command prompt, just type dotnet and check the various options.
image
dotnet
According to the options, let’s start by running dotnet new command.
image
dotnet new
You can see some new files got created in the folder.
image
Project Folder
Here the Nuget.Config file contains the nuget v3 endpoints for grabbing .NET core libraries. The Program.cs is a simple application which will print “Hello World” to the console. The project.json will contain project’s dependencies, project’s target frameworks etc.

Next step is building the project. For that we can run dotnet restore command.
image
dotnet restore
When you run dotnet restore for the first time, you will see that a lot of libraries getting downloaded from nuget. Since I have already ran dotnet restore before for other projects, it has already downloaded the libraries into .dnx folder located in C:\Users\[user].

Once the package restoration completes, you can run dotnet run.
image
dotnet run
You don’t need to compile, the run command would do a compile and execute. Now if you examine your project folder, you will see that bin folder is created and there is a .dotnetrun folder and it has no assemblies there.
image
.dotnetrun Folder
If you want to get the assemblies, you can run dotnet compile command.
image
dotnet compile
And now if you examine the folder, you will see a folders created “bin\Debug\dnxcore50”, and you can find the executables there.
image
dnxcore50 Folder
Happy Coding.

Regards,
Jaliya

Tuesday, January 5, 2016

Using JSHint with an ASP.NET 5 Web Application

JSHint is one of the most popular JavaScript Code Quality Tools which is widely been used among the JavaScript developers. In this post let’s see how we can use JSHint with an ASP.NET 5 application using Visual Studio 2015.

First let’s create an ASP.NET 5 Web Application.
image
ASP.NET 5 Web Application.
Then from the Solution Explorer, under the project, expand “Dependencies” node. Right click on “npm” folder and open up the package.json file.
image
Open package.json
Add the “gulp-jshint” devDependency as follows (last line).
{
  "name": "ASP.NET",
  "version": "0.0.0",
  "devDependencies": {
    "gulp": "3.8.11",
    "gulp-concat": "2.5.2",
    "gulp-cssmin": "0.1.7",
    "gulp-uglify": "1.2.0",
    "rimraf": "2.2.8",
    "gulp-jshint": "2.0.0"
  }
}
Upon saving of the file, you will notice that relevant packages are getting downloaded/restored.

Next step is to modify the gulpfile.js and add a new task to run JSHint.

For that Open up the gulpfile.js and include the “gulp-jshint” plugin as follows (last line).
var gulp = require("gulp"),
    rimraf = require("rimraf"),
    concat = require("gulp-concat"),
    cssmin = require("gulp-cssmin"),
    uglify = require("gulp-uglify"),
    jshint = require("gulp-jshint");
And then add a new gulp task to run the JSHint.
gulp.task('jshint', function () {
    gulp.src("./wwwroot/" + "js/**/*.js")
      .pipe(jshint())
      .pipe(jshint.reporter('default'));
});
Now that is it. Open up the Task Runner Explorer and you should be able to see the new jshint task you have just created.
image
Task Runner Explorer
For testing the task, first let’s add some JavaScript codes to js files where the jshint task is watching. We have mentioned that jshint task is watching .js files inside wwwroot/js folder. In the default ASP.NET 5 project template there is a file named site.js, we can easily modify that.

I am adding following code there and you might notice that there are couple of issues with the code.
// Write your Javascript code.
 
"use strict";
 
function sayHello() {
    return 'Hello World!';
}
 
sayHello()
 
sayHelloWorld();
To find out what are those, from the Task Runner Explorer let’s run the jshint task.
image
Task Runner Explorer
image
Task Runner Explorer
As you can see jshint is showing up the list of issues. Even we can bind the task to run once the project is built.
image
Task Runner Explorer
So when the project is built, you will see the list of issues (if any) in the Task Runner Explorer. So now you can start fixing those.

Happy Coding.

Regards,
Jaliya

Sunday, January 3, 2016

Received Microsoft MVP Award in Visual Studio and Development Technologies

Received the precious Microsoft Most Valuable Professional (MVP) Award for the third consecutive year. And this time in Visual Studio and Development Technologies. In the last two years, I have been awarded MVP for Visual C# and then .NET.

Looking forward for a year filled with action on top of Microsoft Development Stack.
MVPLogo_thumb[2]
Microsoft Most Valuable Professional (MVP)
Thank you Microsoft for your appreciation and Thank you Fiqri Ismail, Wellington Perera, Chaminda Chandrasekara and all the people for your continuous support.

Happy Coding.

Regards,
Jaliya