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]

Entity Framework Basics


What is Entity Framework (EF)?

Microsoft has defined the Entity Framework in following words:

The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database.

ORM is a tool for storing data from objects to relational database like MS SQL Server in an automated way without much programming. Other well known ORM frameworks for .net are DataObjects.Net, NHibernate, OpenAccess, SubSonic etc. ADO.NET Entity Framework (Open source) is from Microsoft.

Please note: Entity framework not only supports MS SQL Server, but also other database like Oracle, DB2, MySQL etc.

Types of Entities in Entity Framework:

1. EntityObject

2. POC (Plain Old CLR Object)

3. POCO Proxy

4. Self-Tracking Entities.

Each entity can have two types of properties, Scalar properties and Navigation properties.

Scalar properties are properties whose actual values are contained in the entity. Whereas Navigation properties are pointers to other related entities.

Modeling techniques using Entity Framework 4.1

1. Code first

In the Code First approach, You write your classes first and then create database from these classes. There are two new objects introduced for Code First approach, DbContext and DbSet. DbContext is the primary object for interacting with a database using a specific model. DbSet(Of TEntity) is used to perform CRUD (Create, Read, Update and Delete) operations against a specific type from the model in Code First approach.

2. Model First

In Model First approach, you create Entities, relationships, and inheritance hierarchies directly on EDMX File. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’.

After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’ to generate the database.

3. Database First

In the Database First approach, you will 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 classes that you interact with in your application are automatically generated from the EDMX file.

We will see examples of this approaches in upcoming articles to clear the terms more better.

Please comment below for any doubts or questions.

Step By Step Installing Visual Studio Professional 2013 RC


In this article, let’s see how to install Visual studio Professional 2013 RC (Release Candidate).

Please note: The installation for Visual studio (VS) Ultimate and Premium 2013 RC is almost simillar to VS Professional 2013 RC installation.

Steps to install VS Professional 2013:

1. First download Visual Studio Professional 2013 RC from here. Setup is around 3 GB. I recommend to download dvd iso image file.

You can also refer this post for new features in the VS 2013 RC.

2. Mount .iso file (if downloaded) , you will see following list of files.

3. Click on vs_professioanl.exe file to start the installation. You will see following screen first.

4. Read the license terms and privacy policy and accept them by selecting the checkbox in from of them. Click on “Next” button.

5. Select the features you want to install then click on “INSTALL” button to start the installation.

Setup will create system restore point first before installing VS 2013 components.

6. Once it’s done, setup will start acquiring the required components to install and will start installing core features. It will take few minutes to install it. You may required to restart your system (for once ONLY) in between the setup.

7. Once it finishes the setup, you will see the success screen as below.

8. Click on “Restart Now” button to restart your system. After restarting your system, you are now ready to use your VS Professional 2013 RC.

Here you are done with the installation of the Visual Studio Professional 2013 RC.

Now Just open the installed VS 2013 program from your system. You will see following welcome screen. You can sign in to your Microsoft account by clicking on “Sign In” button, else you can just skip the step by clicking on the “Not now, maybe later” link.

If you sign in with your Microsoft account, Visual studio will sync your VS settings between different devices and connect to online developer services.

9. If you click on the “Sign in” button, you will see the following screens.

10. If you are not interested to sign in, you can just skip this step and can sign in to your Microsoft account later. Once you have done with that, you will be asked to select a theme for your visual studio. You can select either Blue, dark or light theme. Also you can set your development settings from the screen. Off course you can change these settings later at any time.

11. Now click on the “Start Visual Studio” button to launch the application.

Search Engine optimization (SEO) Basics


In this article, Let’s discuss about Search engine optimization (SEO) basics.

What is SEO?

Search Engine Optimization (SEO) is the process of improving the ranking of a website on Internet search engines. In general, higher ranked on the search results page and more frequently a site appears in the search results list, the more visitors it will receive from the search engine’s users. Here is the list of search enginesGoogle is the most popular search engine in the world.

SEO Basics:

1. Create unique, accurate page titles

A title tag tells the search engines about the topic of a particular page. The <title> tag should be placed within the <head> tag of the HTML document. Ideally, you should create a unique title for each page on your site.

2. Use brief and descriptive titles

Page titles are an important aspect of search engine optimization. Titles can be both short and informative. If the title is too long, Search engines will show only a portion of it in the search result.

3. Accurately describe the page’s content

Your page content should accurately describe about the title and topic. Avoid using default titles like “Untitled” or “New Page 1”.

4. Make use of the “description” meta tag

A page’s meta tag gives search engines a summary of what the page is about. Like the <title> tag, the description meta tag is placed within the <head> tag of your HTML document.

5. Improve the structure of your URLs

Creating descriptive categories and filenames for the documents on your website can not only help you keep your site better organized, but it could also lead to better crawling of your documents by search engines. Choose a URL that will be easy for users and search engines to understand!

7. Create a simple directory structure

Use a directory structure that organizes your content well and makes it easy for visitors to know where they are at on your site.

8. Prepare sitemaps

A site map is a file (generally xml file) on your site that displays the structure of your website. An XML Sitemap file, which you can submit through search engine’s Webmaster Tools, makes it easier for them to discover the pages on your site.

9. Create fresh, unique content

New content will not only keep your existing visitor base coming back, but also bring in new visitors.

10. Make effective use of robots.txt

A robots.txt file tells search engines whether they can access and therefore crawl parts of your site. This file must be named robots.txt, is placed in the root directory of your site.