Posts filed under Using Entity Framework

Using Microsoft’s Entity Framework: Part 6 of 6

Reduced Development Time

In the first blog in this series, we provided a comprehensive introduction to Microsoft's Entity Framework. Going forward, we addressed the creation of custom web applications, and creating a data access layer. In the next post, we went into identifying a couple of the more common EF issues and how to troubleshoot them while the most recent installation taught us about creating a scaleable application. For our final post, we’ll talk about how EF can actually reduce development time.

The beauty of Entity Framework is the way that it reduces development time when you launch a new project. It has done a great deal of the preliminary work for you by reducing the time required to write the data access layer. Not only that, but you can save time down the road when revisions or modifications must be made.

If you have dealt with systems that degrade over time, the results being slow and inaccurate, you realize how the handling of data can make or break a system. The Entity Framework allows developers to manipulate conceptual objects, such as products, messages, etc. This mapping ability allows developers to store data efficiently. Working between a database and code can be time consuming and can provide yet another area for errors. However, Entity Framework has taken that part of the work and prepared it in advance.

Not only does this system make programming easier and faster, but it allows for portability since changes in the database software require a mere change in the mapping software interface rather than in the code itself. By steering clear from a database model and using objects instead, you can design a system conceptually, thereby saving time and gaining flexibility. By layering your software, you can use business logic throughout the model so that each layer of code performs its own function, thus separating the needs and concerns along the way. This approach, with separation built in, creates a defined method of organizing or modeling the system according to the needs.

SQL is a time stealer that takes energy and time and hides it away, never to be found again. While many developers have grown to understand SQL deeply and are very comfortable with it, there are others who may not have a thorough understanding when it comes to using SQL for complicated scenarios. A little mistake or a line of code that is not optimized can create issues that cause problems down the road. Not only that, but troubleshooting can be difficult. These issues can come up even for experienced developers.

When one has new developers, the use of Entity Framework would be much more time effective and less susceptible to mistakes. By using the higher level language, you can write a query and allow the Entity Framework to generate the ideal SQL commands quickly and accurately. Not only is the work done for you, but it is easier to document and read the code. This not only saves you money and time now, but can save a great deal of effort down the road when modifications are necessary. Imagine being able to go into a layer of code and merely make the changes necessary there without delving into the data interface layer.

By moving away from database-first systems, you can lean on a higher-level tool that can allow you to grow and expand to more complex application scenarios without 'reinventing the wheel' every time you take a step in a new or expanded direction.

Posted on October 23, 2015 and filed under Using Entity Framework.

Using Microsoft’s Entity Framework: Part 5 of 6

Creating a Scaleable Application

In the first blog in this series, we provided a comprehensive introduction to Microsoft's Entity Framework. Going forward, we addressed the creation of custom web applications. The third outlined creating a data access layer and the fourth was really helpful in identifying a couple of the more common EF issues and how to troubleshoot them.

So, now that you have some understanding of how Entity Framework actually works, you are ready for the next step in understanding why this is such a positive solution for your business. So how does Entity Framework allow developers to create a more robust and scalable application? Without getting too technical, an example is probably the best way to show you just how useful this can be.

Generally, when you are using a database there is a great deal of tedium involved in constantly adding new information, making sure it falls into the right categories and writing the particular language to keep things up to date. As we’ve discussed, Entity Framework is an open source framework provided by Microsoft that does a great deal of the busy work for you.

Let us take a moment to look at an example that may be used by a school. The school is the domain in which everything is stored within the database. As students rarely make a career out of going to high school, the database is constantly changing and each student has their own particular attributes that need to be tracked. These attributes can vary from GPA to days missed to the type of classes they are taking. To keep this information updated traditionally, a great deal of language would need to be updated each time to create an accurate database. With Entity Framework, the attributes are added to each student and the framework does the busy work to make put them in the right areas of the database.

This allows you to create classes with different connection with much more ease and at a faster rate. While the code generator in the framework may not be as robust as what will be written by an engineer, once the groundwork is done, Entity can handle the rest with ease.

In addition Entity offers T4-like template code generation. With predefined templates that can generate code in C# or Visual Basic for the model that can support persistence aware and persistence ignorant entities. It also supports validation framework for entity property values validation MVC Controller and views, Data Annotations metadata classes and a wide variety of other technical aspects that in short, makes life easier for everyone involved in a project.

You will also have the option to update to and from database with wizards that allow you to synchronize with ORM models in any direction automatically. A wide variety of mapping is supported as well, from entity to table, table splitting and complex types just to name a few. Unlike EDM designer Entity does not require manual XML code editing regardless of how complex it may be.

While this is a very high level overview of what is on the table when it comes to incorporating Entity Framework into your business, it is paramount to understand that this was designed to make a developer’s job much easier. It succeeds at that in spades and the fine folks here at Extra Nerds will be happy to discuss how we can help with your next project.

Stop back next week for our sixth and final installation in this series which will tell us how Entity Framework reduces development time.

Posted on October 16, 2015 and filed under Using Entity Framework.

Using Microsoft’s Entity Framework: Part 4 of 6

How to Troubleshoot Common Issues

Continuing from the first parts of the series when we provided an introduction, a follow up on creating web applications, and a third on creating a data access layer, this fourth installment will be detailing the troubleshooting of common problems that may be encountered during the Entity Framework process. This will help those who are constantly encountering issues from the Microsoft program, a process that is often very frustrating and in some cases, difficult. Here is a basic guide which some may find to be helpful.

Troubleshooting Tips

There are various things that can go awry when using Entity Framework. Rather than going through all of them, I will address the most common problems and remedies. Below are what I found to be the most consistent problems, as well as the highest source of complaints for those using Entity Framework.

Cannot Connect to a Database. For those who have gotten this error message, chances are you were unaware on how to handle it. That’s alright as clear instructions for dealing with these cases have not been readily available. So, how do you troubleshoot this problem? First, look into the connection settings that you have tied with the framework. Once you have found the connection hotspot, you will be able to tell the exceptions connectivity. Once a connection is found, it is recommended that you run a “debugger” to find the full source of the problem. After you have run the debugger, though absent of an exact code or configuration, the Entity Framework will most likely actively try to connect to a local SQL Server Express database that should be available. Through a quick configuration test, you can find the source of the problem, which 99% of the time is related to the absence of LocalDb. Install LocalDb and, once installed, choose to connect to this, rather than the SQL Server Express, and you should find that these connection problems are removed.

Cannot Attach to Deleted MDF File. Another common problem for those using Entity Framework is the inability to attach to a deleted MDF File. When those using SQL LocalDb delete files, the process is only completed when they use Object Explorer in Visual Studio, or in other cases, SQL Server Management Studio. The reason for this error is simple: the database of the file is still tied to LocalDb. Luckily, the solution is just as simple as the problem. You simply need to go to Object Explorer, find the file then delete it from this location. SQL servers should then recreate the files that were once deleted so that you can attach any additional information.

In Conclusion

These are certainly not the only problems that you could encounter, but they are generally the most common. For any other problems, just know that they are usually rooted in the database or in the connection of the files. Of course, other methods do exist to fix these problems, but for now these are the most simple and painless.

In our next post in this series, we’ll outline how Entity Framework allows developers to create more robust and scaleable applications so stay tuned!

Posted on October 9, 2015 and filed under Using Entity Framework.

Using Microsoft’s Entity Framework: Part 3 of 6

How to Create a Data Access Layer

As we mentioned in the introductory blog in this series as well as the post on creating custom web applications, Entity Framework (EF) is an object-relational framework (ORM) that is Microsoft's recommended data access technology usually on new .NET applications development. Basically, it allows the developer to work easily with relational data using domain-specific objects and without hard code database access. With my experience in building .NET applications, I'll be showing you how to create a data access layer using Entity Framework.

To create the entity data model (EDM) or the conceptual model for the entities of your domain, EF provides three models including model first, database first and code first. With the code first and model first approaches, it's assumed that a database schema is created based on the model you also need not have an existing database as you create your application. This is because database administrators (DBAs) are responsible for designing and maintaining database within enterprise environments and not the developers. In this post, we take a look at the database first option where the entity data model becomes a virtual reflection of the database or any of its subsets.

CREATE TABLE [dbo].[Department] (
[DepartmentId] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([DepartmentId] ASC)
);

CREATE TABLE [dbo].[Employee] (
[EmployeeId] INT IDENTITY (1, 1) NOT NULL,
[DepartmentId] INT NOT NULL,
[FirstName] VARCHAR (20) NOT NULL,
[LastName] VARCHAR (20) NOT NULL,
[Email] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([EmployeeId] ASC),
CONSTRAINT [FK_Employee_Department] FOREIGN KEY ([DepartmentId])
REFERENCES [dbo].[Department] ([DepartmentId])
);

The N-tier architecture

Normally, large enterprise applications will require more than one database to store their data and a data access layer (DAL) to read the databases. Repositories may also exist to communicate with DAL, business layer for logic, classes for business domain, service layer for displaying the business layer to the clients and finally a user interface such as ASP.NET application which I normally use in my case or a WPF desktop application.

Creating Data access layer (DAL)

1. Start by creating a new C# class library example (Mm.DataAccessLayer) and add an ADO.NET Entity Data Model. This is how I like to start off. In the Entity Data Model wizard, choose "Generate from database". The wizard allows you to connect the database selecting the Department and the Employees to be included in the model.

2. In order to separate entity classes from EMDX which is vital separation is of importance, add a new class library (Mm.DomainModel) using visual studio, my favorite to the solution.

3. Open the File Explorer and move the Model.tt file to your new project. folder.

4. Include Model.tt file back in Visual Studio in the created project by clicking   
"Include In Project" option on the "Show All Files" icon.

5. Delete Model.tt file from DAL project.

6. In the Model.tt template file, set the inputFile variable to point to an explicit path
where to find the model.

As Follows: const string inputFile = @"../Mm.DataAccessLayer/Model.edmx";

Right-click on your Model.tt template and choose the "Run Custom Tool" to regenerate and reflect the latest changes to that model.

7. As you well know, the context by default expects the entity classes included in the same namespace. For their new namespace you need to add a using statement to your Model.Context.tt template file of your DAL project.

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using Mm.DomainModel; <!-- Added -->
<#
if (container.FunctionImports.Any())
{
#>
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
<#
}
#>

8. All you need now is to add a reference from your DAL project to the domain model project and compile it.

Hopefully this post has been helpful to you in creating a data access layer. The next installment in the Microsoft Entity Framework series will concentrate on troubleshooting common problems.

Posted on October 2, 2015 and filed under Using Entity Framework.

Using Microsoft’s Entity Framework: Part 2 of 6

Creating Custom Web Applications

In the first installment in this series, we just showed the basics in order to provide an informational foundation on Microsoft’s Entity Framework. Since that post was some time ago, let's review and also talk about why .NET and Entity Framework is ideal for creating custom web applications.

If you’re a business owner who aims to use the power of IT to grow your firm, you always want to find tools that can help you to achieve the best results. To that end, let’s talk about .NET and Entity Frameworks, some of the best technologies which are ideal for the creation of custom web applications. It is surprising that there are IT directors who still do not use these tools despite the fantastic value that they hold. In fact, you will be baffled at how quickly you can use them to overcome some of the challenges that have been hindering the growth of your organization.

Entity Framework explained

Commonly referred to as EF, Entity Framework is an incredibly useful object relationship mapper that enables .NET developers to work on data through the use of domain specific objects. The primary goal of EF is to make it easy for developers to focus more on the domain of the business as opposed to the writing of database plumbing codes. These connections include things such as data tables, commands, datasets, and links. By doing this, an IT technician will find it easier to overcome most of the challenges associated with this job.

How it actually works

For many years, web developers used other options such as ADO.NET to create utility libraries. Although this was successful, some found it difficult to pull vital data from the database without having to write data access codes that were both repetitive and confusing. With time, the entire process became boring to most experts and so they had to look for alternatives. The fact that EF is the preferred data access layer for Microsoft means that working with it can flawlessly move a project forward so it can easily get rid of the repetitive procedures.

Installing and using Entity Framework

To use EF, you will have to, of course, install it first. The best part is that even with the fantastic benefits that it brings, installing it is quite an easy process. Although there are other ways of installing it, the most effective one is to download and install it from Nuget. It is as easy as right-clicking on the preferences in your project and following the prompts. Once you find the Nuget packages, everything else will be simple. An alternative of doing this is using a package manager console. You can then go ahead to create a model of an existing database depending on the particular project that you want to work on ad how you want to do it. We reviewed this process in depth in our first installation when discussing how to get started.

Undeniably, .NET and Entity Framework are technologies that are really worth the investment. Regardless of the nature of your business, there is no doubt that success will come much easier once you have these technologies in place. To discuss your next potential project, and how to use technology to increase your profits while reducing your daily workload, just contact Extra Nerds today. And stop back next week when we discuss how to create a data access layer using Entity Framework.

Posted on September 25, 2015 and filed under Using Entity Framework.

Using Microsoft’s Entity Framework: Part 1 of 6

Getting Started

In this first installment of the Using Microsoft's Entity Framework series, we will start with the basics.

Entity framework (EF) is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. EF’s main goal is to help developers focus on the business domain, rather than writing database plumbing code (e.g connections, commands, etc, data tables and datasets).

For years, I have worked with classic ADO.NET and have created my own utility libraries to push and pull data from the database. Although this worked flawlessly, writing repetitive data access code got old and boring. EF is also Microsoft’s preferred data access layer with projects moving forward. ADO.NET and LINQ to SQL are not going away anytime soon (there are still a lot of applications that uses these), but both technologies will no longer receive or have little investments from Microsoft.

So, let’s dive in and get started on how to start using entity framework on a project.  The latest version of EF (as of this writing) is 6.01.

Install Nuget via Visual Studio Extension Manager

If you have the Nuget package manager already installed in Visual Studio, skip this step otherwise referred to Nuget Package Manager installation instructions.

Installing EF via Nuget

The fastest and easiest way to install entity framework is to download and install it from Nuget. On your project, you may simply right click on References and click on Manage Nuget Packages.  Alternatively, you may also use the Package Manager console (Tools -> Library Package Manager -> Package Manager console) to run the EF powershell installation command.  To get more help on how to run the package manager console, see Nuget Package Manager Console PowerShell Reference

One key thing to remember is that if your application is targeting to run on .NET 4.0, then the default EF assembly version will be 4.4.  Applications running on .NET 4.5 and above will use the default assembly version 5.0.

Visual Studio.NET FrameworkDefault EF versionEF after NUGET

VS 20104.04.0

VS 20124.04.46.0

VS 20124.55.06.0

 

Create A Model Of An Existing Database (Database First Approach)

After EF is installed, some entries will be added on the web.config/app.config file related to Entity Framework.  Now that EF is installed, let’s see how we can add a model of an existing database.  Note that there is also a Code-First approach where you typically build the database from scratch in C#, but for simplicity’s sake, let’s just start with an existing database.

1.  Right click on your project and click on Add New Item

2.   Select the ADO.NET Entity Data Model option from the templates list

3.   Follow the steps on the Entity Data Model Wizard and specify the connection string to your database

4.  Select all database objects you want to include in your model


Posted on January 15, 2015 and filed under Using Entity Framework.