Monthly Archives: October 2013

Entity Framework – Database First Approach Example


In this article, Let’s see an example of Entity Framework – Database First approach

If you don’t know about Entity Framework, please go through this article.

Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The poco classes are automatically generated from the EDMX file.

Entity Framework – Database First Approach Example

1. Let’s create a console application. Name it as “EFDatabaseFirstExample”.

2. We will create a model by using Entity Framework Designer for our existing database. Let’s add a new item to our project “ADO.NET Entity Data Model”.

3. It will start a wizard, now as we have existing database, we will select “Generate from Database”.

4. Choose the connection string, pick a connection to our existing database and click on “Next” button.

5. Wizard will ask you to pick the Entity Framework version to use. Just select the latest version and click “Next”.

6. Now choose the database objects like tables, views, stored procedures etc from the screen.

7. Model is created now and you can see the entities.

8. During the process when you select Entity Framework version, the reference to Entity Framework Assembly is automatically added.

So after step 7, you will see following things in the project.

9. Since everything is in place, let’s code to add a employee for a company and display all the employees for a company.


Console.WriteLine("Please enter employee name");
using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
{
Employee employee = new Employee();
employee.Name = Console.ReadLine();
employee.CompanyId = 1; //hard coded for demo purpose
employee.Age = 27;
db.Employees.Add(employee);
db.SaveChanges();
}

Console.WriteLine("List of employees for company 1");
using (var db = new EFDatabaseFirstExample.EFDatabaseFirstDBEntities())
{
//get the company with ID = 1
var company = (from c in db.Companies
where c.Id == 1
select c).SingleOrDefault();

//get the employee list for a company with a id = 1
List<Employee> employees = company.Employees.ToList();

//display each item.
foreach (var emp in employees)
{
Console.WriteLine(emp.Name);
}
Console.ReadKey();
}

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

Entity Framework – Model First Approach Example


In this article, Let’s see an example of Entity Framework – Model First approach

If you don’t know about Entity Framework, please go through this article.

Model First allows you to create a new model using the Entity Framework Designer and then generate a database schema from the model.

Entity Framework – Model First Approach Example

1. Let’s create a console application. Name it as “EFModelFirstExample”.

Add a reference to the “Entity Framework” using nuget package manager. If you don’t know how to add a reference using Nuget, please refer this post.

2. We will create a model by using Entity Framework Designer. Let’s add a new item to our project “ADO.NET Entity Data Model”.

3. Once you click on “Add”, there are 2 options, either you can create a model using existing database or you can start it by creating empty model. In this project, we will create an empty model.

4. Once you “Finish” it, you will see that an empty file called “Model1.edmx” is added into your project. Open it and right click on it and select Add New and click on Entity to create a new entity.

5. For this example, we will consider a simple Company-employee relationship and create entities for them.

6. Right click on it and Add new scalar property called “Name” and “Address”.

7. Now follow the same procedure for “Employee” entity. Add “Name” and “Age” scalar properties to it.

Once it’s done, we need to set the association between those 2 entities. Right click the “Company” entity and click “Add New” – “Association”.

8. Check the “Multiplicity” option and set it for our entities. In our case, it’s one to many. (a company – many employees)

9. Entities and their relationship will look like as show in the screenshot below. Just right click on the “edmx” file anywhere on the screen and click on “Generate Database from Modal” to generate database for our defined entities.

10. Once you click on “Generate Database from Modal”, you will be asked to set connection string for your database.

11. Then from the following screen, select “Microsoft SQL Server” and click “Continue”.

12. Enter the Server Name, credentials and Database name.

13. If you are creating a new database, you will see following screen. Just click “Ok” as it will create a new database only.

14. Once done, select “Yes” or “No” (include or exclude sensitive data in connection string) and Click “Next” button.

15. Finally review “Summary and Settings” and click on “Finish” button.

16. You may see following screen once you finish the wizard. Just ignore it and click “Ok”.

17. A file called “Model1.edmx.sql” will be created and added to the project. Open it and right click, then select “Execute”. It will create tables and constraints in the database.

18. Since entities are automatically created, we can directly use it in the code.

If you just expand the “Model1.tt”, you can see the classes “Company.cs” and “Employee.cs” are auto created during the process.

19. Now let’s write a sample code which will add a company record and display it on the screen.


Console.WriteLine("Please enter a company name.");
string companyName = Console.ReadLine();

Console.WriteLine("Please enter a company address");
string companyAddress = Console.ReadLine();

EFModelFirstExample.Company company = new Company();
company.Name = companyName;
company.Address = companyAddress;
using (var db = new DBContext())
{
db.Companies.Add(company);
db.SaveChanges();
}

Console.WriteLine("List of companies in the DB");
using (var db = new DBContext())
{
var companies = (from c in db.Companies
select c.Name).ToList();
foreach (var name in companies)
{
Console.WriteLine(name);
}
Console.ReadKey();
}

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]

Box.com [Direct Download Link]

 

Bootbox.js – Alert, Confirm, Prompt and Dialogs for Bootstrap framework


Bootbox.js is a small JavaScript library developed on top of the Twitter’s Bootstrap which allows you to create programmatic dialog boxes like alert, confirm, prompt etc. In short, it’s a wrappers for JavaScript alert(), confirm() and other flexible dialogs using Twitter’s bootstrap framework.

Only following line of code will display a Bootstrap alert.


bootbox.alert("Hello world!");

But if you try to achieve it via Bootstrap, you need to write multiple lines of code.

See it here in action.

Core Methods of Bootbox.js

  • bootbox.alert(message, callback)
  • bootbox.prompt(message, callback)
  • bootbox.confirm(message, callback)
  • bootbox.dialog(options)

Before we look into examples, let’s see dependencies of bootbox.

Since we know that Bootbox is developed on top of Bootstrap, it is required.

Css Dependencies:


<link rel="stylesheet" type="text/css" href="bootstrap.min.css">

Javascript (JS) dependencies:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 <script src="bootstrap.min.js"></script>

Examples

1. Alert


$(document).ready(function () {

 bootbox.alert("Hello world!");

});

Live Demo

2. Confirm

$(document).ready(function () {

bootbox.confirm("Are you sure?", function(result) {
 alert('You clicked: ' + result);
});

});

Live Demo

3. Prompt


bootbox.prompt("What is your city?", function(result) {
 if (result === null) {
 alert("Prompt dismissed");
 } else {
 alert("Your city is " + result);
 }
});

Live Demo

4. Dialog

bootbox.dialog({
 message: "Custom dialog using Bootbox",
 title: "Bootbox Dialog",
 buttons: {
 success: {
 label: "Yes",
 className: "btn-success",
 callback: function() {
 alert("You clicked Yes");
 }
 },
 danger: {
 label: "No",
 className: "btn-danger",
 callback: function() {
 alert("You clicked No");
 }
 },
 main: {
 label: "Not Sure",
 className: "btn-primary",
 callback: function() {
 alert("You clicked Not Sure");
 }
 }
 }
});

Live Demo

Please note: It’s not necessary to call Bootbox API on document.ready, it’s for demo purpose only. You can call Bootbox API on any event.

Peek Definition in Visual Studio 2013


In this article, let’s review a new handy feature in Visual Studio 2013 called Peek Definition .

Generally when you want to view a method, you point a mouse cursor on a method name and right click on it and click “Go To Definition” (F12 shortcut key).

Once you do that, you will go to the file where method is declared or defined.

Using Peek Definition

This feature is similar to “Go To Definition” except in-file editing (which we can describe it as view or edit in a same file without losing your place) as explained below.

When you right click on a method by placing a cursor over it and clicking on “Peek Definition” (ALT + F12 shortcut key), you won’t leave your current file/location instead a small window will appear over there.

This makes it very easy to view as well as edit a method definition without losing your place in the current file.

How to Install a NuGet Package in Visual Studio?


In this article, let’s see what is NuGet and how to install a NuGet Package in Visual Studio.

About NuGet

It is a free and open source package manager for the .NET Framework. It was formerly known as NuPack. The NuGet Gallery (nuget.org) is the central package repository used by all package authors and consumers.

When you install a package, NuGet copies all the required files to your project/solution and makes appropriate changes such as adding a reference to assembly, changing app.config or web.config file etc.

In short, You can include a Javascript file reference or add an assembly reference via NuGet Package Manager in Visual Studio. We don’t need to worry about dependent packages as it is automatically handled and included in the project by NuGet.

NuGet Package Manager Extension for Visual Studio

It is a collection of tools to automate the process of downloading, installing, upgrading, configuring, and removing packages from a Visual Studio Project/solution. It is distributed as a Visual Studio extension.

Installing NuGet Package Manager Extension

1. If the NuGet Package Manager is not installed on Visual Studio, you can install it by clicking on Tools > Extensions and Updates from the menu.

Clicking on “Extensions and Updates”, you will see following screen.

2. Select “Online” from the left hand side, you will see a list, sorted by Most popular packages. Select “NuGet Package Manager” from it and click on “Download” button to install it.

You will see following screens.

3. As show in the screen below, accept the license terms, click “Install” to continue.

Once installation is done, You will see this screen. Click on “Close” button.

4. You will be asked to restart the Visual Studio. Now you have NuGet Package Manager extension installed in Visual Studio. A small green checkbox icon is appeared against the installed extension.

More information about Nuget Package Manager extension can be found here in the visual studio gallery.

Installing NuGet Packages in Visual Studio

Basically there are 2 ways to install a NuGet Package in Visual Studio. First is via User interface window and other is via package manager console.

  • Installation via NuGet interface window

1. RIght click on your project from solution explorer and click on Manage NuGet Packages. Select the “Online” link from the left hand side and find the required package.

2. Click on “Install” button from the screen. Package manager will do all the stuff in the background for you.

2. If you see references in your project, reference for the installed package is added.

Here in this case, it’s json.NET package.

  • Installation via Package Manager Console

1. From the Tools menu, select Library Package Manager and then click Package Manager Console.

You will see following screen in Visual Studio.

2. To search a package, type a command Get-Package -ListAvailable -Filter <package name>

e.g Get-Package -ListAvailable -Filter EntityFramework

3. To install required package, type a command  Install-Package <package name>

e.g. Install-Package EntityFramework

Once installation done, you can see that reference for the package is automatically added to project.

NuGet Intro Video

Entity Framework – The type was not mapped issue solution


While working on the Entity Framework, you may face an issue with the exception saying:

An unhandled exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.dll

The type ‘xxx’ was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.

Here is the console based code which can reproduce this exception:


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
blog.DateCreated = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
}

Solution:

The issue is POCO classes and DbContext was nested within POCO class. Entity framework does not like nested classes.

Please note: Nested class means, a class defined within another class.

Error free code:


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
blog.DateCreated = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}

public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Hope this helps.

Entity Framework – Code First Approach Example


In this article, Let’s see an example of Entity Framework – Code First approach

If you don’t know about Entity Framework, please go through this article.

Just to revise, In the Code First approach, You write your classes first and then create database from these classes.

Entity Framework – Code First Approach Example

1. Let’s create a console application. Name it as “EFCodeFirstExample”.

2. Since it’s Entity Framework project, let’s add reference to “Entity Framework” assembly via nuget package manager.

There are many ways to do it. We can add it by right clicking the project and selecting the “Manage Nuget Packages” menu. A window will appear, select “Online” from left hand side and enter “EntityFramework” on top right hand side, press enter to search. Entity Framework package will appear in search result, press “Install” to continue.

3. Once done, you can see from the project references that the reference to “EntityFramework” is added.

Also we need to add a namespace reference to Entity framework.


using System.Data.Entity;

4. Let’s start with coding part. We will create 2 simple classes (POCO) to understand the code first approach namely “Blog” and “Post”.

Consider following Blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}

5. Consider following Post class


public class Post
{
[Key]
public int IDPost { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int IDBlog { get; set; }
public virtual Blog Blog { get; set; }
}

6. We have specified Key attribute to “IDBlog” and “IDPost”, which means both are primary keys for respective tables (Tables are created once we run the application).

Virtual properties (virtual List<Post> Posts and virtual Blog Blog) are marked for lazy loading, which means when we try to access them, entity framework will load the associated data. Those are called navigation properties, which means they will create foreign key constraints in the DB.

7. Let’s create a context class now. Consider following BloggingContext class.


public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}

Here please note that our BloggingContext class is derived from the “DbContext” class.

8. Now let’s write our main program where we will add a new blog and list the blogs in the DB.


class Program
{
static void Main(string[] args)
{
using (var db = new BloggingContext())
{
// Create and save a new Blog
Console.WriteLine("Please enter blog name:");
string blogName = Console.ReadLine();

Blog blog = new Blog();
blog.Name = blogName;
db.Blogs.Add(blog);
db.SaveChanges();

// List all available blogs in the DB
Console.WriteLine("All blogs in the DB:");
foreach (var item in db.Blogs.ToList())
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
}
}

9. Now you will think about connection string to DB. We did not mention about DB and connection string in the project. By default, visual studio 2012+ has local DB.

By convention DbContext has created a database for you.

1. If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance

2. If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012+)
10. The database is named after the fully qualified name of the derived context, in our case that is EFCodeFirstExample.BloggingContext.

11. Once you run the application, it will create the DB for us upon our defined POCO classes. Here is the output for our application.

12. Now if we need to change the table schema, then what? In such case, we need to change out classes which in turn update our DB. To do this we have a feature in Entity Framework called Code First Migrations, or Migrations.

13. Consider following change in out blog class.


public class Blog
{
[Key]
public int IDBlog { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<Post> Posts { get; set; }
}

14. To update this change in our DB, we need to enable Code First Migrations for our BloggingContext. Open the “Package Manager Console” from the solution and run the command. Enable-Migrations

15. This command will add 2 files in the project named “Configuration.cs” (This file contains the settings that Migrations will use for migrating BloggingContext) and “201310141156476_InitialCreate.cs” (it represents the changes that have already been applied to the database).

16. Now let’s run the command Add-Migration AddDateCreated command in Package Manager Console to update out DB for new changes. It will create a file called “201310141332176_AddDateCreated.cs”


public partial class AddDateCreated : DbMigration
{
public override void Up()
{
AddColumn("dbo.Blogs", "DateCreated", c => c.DateTime(nullable: false));
}

public override void Down()
{
DropColumn("dbo.Blogs", "DateCreated");
}
}

17. Run the Update-Database command in Package Manager Console. This command will apply any pending migrations to the database. You can use the –Verbose switch when calling Update-Database to see the SQL that is being executed against the database.

18 And you will see the DateCreated column is added in our DB.

Hope this helps. Please comment below the post if you have any doubts or questions.

Source Code Download:

Github [Repository Link]