Uncategorized

Using lookup tables (join tables) in Entity Framework

Very rarely, if ever, do we come across a situation in programming where an entire application relies on isolated database tables that do not have share data between each other. So, then, how do you use Entity Framework to help these tables communicate?

Solution: Join Tables

There are several relationship types your Entity Framework Entities can have with each other.

  1. One-to-One
  2. One-to-Many
  3. Many-to-Many

One-to-One can be handled simply by using a foreign key. For simplicity sake, let’s say we have a Dog class and an Adopter class. A dog can only have one adopter and an adopter can only adopt one dog. Here is what the class setup looks like:

Dog Class:

public class Dog  
{ 
    public string Id { get; set; }
    public string Name { get; set; }
    
    public virtual Adopter Adopter {get; set}
}

Adopter Class:

public class Adopter 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string DogId {get; set;}
    
    public virtual Dog Dog {get; set}
}

When this is compiled by Entity Framework, the Id of the Dog with be placed in the virtual Dog column of the Adopter table and the Id of the Adopter will be placed in the virtual Adopter column of the Dog table. And that’s it. Simple.

For a One-to-Many relationship, let’s say an Adopter can adopt multiple dogs (as it should be), but a dog can still only have one Adopter.

This is what the class setup will look like:

Dog Class:

public class Dog  
{ 
    public string Id { get; set; }
    public string Name { get; set; }
    
    public virtual Adopter Adopter {get; set}
}

Adopter Class:

public class Adopter 
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string DogId {get; set;}

    public virtual ICollection Dogs {get; set;}
}

Here, the Dog Class stays the same since it can still only have one Adopter. However, the Adopter class looks a little different. Instead of a single foreign key, we have a collection of Dogs. In the database this looks like a list of Dog Ids.

Finally, we have the Many-to-Many relationship. In this situation, a Dog can have many Adopters and and Adopter can have many Dogs. Now, following the pattern above, you may think that we would just set up a virtual collection in both the Dog and Adopter classes. This, however, is not the case. Instead, we need what is called a Binding or Join Table.

Join Tables allow Many-to-Many relationships in Entity Framework by matching the necessary data (normally an Id).

Here is what our classes will look like:

Dog Class:

public class Dog  
{ 
    public string Id { get; set; }
    public string Name { get; set; }
    
    public virtual ICollection AdoptionMember {get; set;}
}

Adopter Class:

public class Adopter 
{
    public string Id { get; set; }
    public string Name { get; set; }
    
    public virtual ICollection AdoptionMember {get; set;}
}
public class AdoptionMember 
{
    public string Id { get; set; }
    public string AdoptionDate { get; set; }
    public int AdoptionFee { get; set;}
    public string DogId {get; set;}
    public string AdopterId {get; set;}
    
    public virtual Dog Dog { get; set; }
    public virtual Adopter Adopter { get; set; }
}

Notice that there is a third class, the AdoptionMember. Both the Dog and Adopter classes will have a collection of the AdoptionMember class. The AdoptionMember class has single Foreign Keys for each the Dog and Adoption classes. The AdoptionMember class also has shared data such as the Adoption Date and the Adoption Fee for each individual adoption.

This is a very basic overview of the most common data relationship types you will run into using MVC and how to set up your data when using Entity Framework Code First method.

Advertisement
Uncategorized

Selectable Enum Dropdown List Using TagHelpers

This post is going to look into how populate a dropdown list with the contents of an enum using a TagHelper and an HTML Helper.

In case you aren’t familiar with TagHelpers, TLDR:

TagHelpers use server-side code to render HTML concisely and is readable for those not familiar with Razor markup.

If you want to learn more, checkout the docs here.

Alright, let’s dive in with our setup!

Enum:

public enum DogName
{
       Fido,
       Buddy,
       Bear
}

Model:

public class Dog
{
      public DogName DogName{ get; set; }
}

Make sure both the class and property are public.

View:

In the beginning of your view, be sure to bind the Model:

@model RescueShare.Models.Dog

Then, using our <select> TagHelper in our Razor View to create the actual dropdown:

<select asp-for="DogName"
asp-items="Html.GetEnumSelectList<DogName>()">
</select>

The asp-for attribute binds the values to the DogName property. Then, asp-items populuates the dropdown with values from our DogName enum using our GetEnumSelectList HTML Helper.

Here are the major benefits for using a TagHelper in this scenario:

  1. Ability to access server-side data
  2. Concise and easy to read
  3. Works with Intellisense

And that’s it! We have gone through how to successfully bind a <select> TagHelper to an enum in a Razor View using an HTML Helper for an ASP.NET Core MVC app!

Web App Series

Basics of .NET Web Apps – Part 3: MVC

Welcome back! Now that we have our environment set up, this post is going to go into more detail about the MVC (Model-View-Controller) design pattern and how it helps us write clear and reusable code.

If this is the first post of the series you are reading, everything should make just as much sense to you as it would if you were following along. However, if you need help setting up your environment, feel free to check out the first two posts here and here.

Let’s dive in!

First, what is a design pattern? A Design Pattern is a commonly used solution to commonly encountered problems. The problem MVC handles, is how to separate business logic from what the end user sees. The reason I’m choosing to use MVC is because it is relatively simple to understand and implement and has a solid community around it (MVC has been around since the 70s but has been an official project type if ASP.NET for about 10 years).

Let’s break it up.

M (Model) – The model is where you hold your business logic and data.

V (View) – The view is what the end user sees and interacts with. We will be setting up our views using Razor syntax.

C (Controller) – The controller is how the model and view communicate and decides which view to render to the user.

The flow looks a little like this:

The Controller renders data from the Model to the View, deciding which view the user needs to see. The user sees the View and sends requests back to the Controller. The Controller then updates the Model. The Model accesses data from the database and sends the data back to the Controller that sends the data up to the View for the user.

Here is a way to visualize:

MVCFlow

Let’s walk through an example using our handy Dog class.

First, let’s create out Model.

We set up our dog class in Part 2 and it looked a little like this:

namespace RescueShare.Models
{
public class Dog
{
public string ID { get; set; }
public string Name { get; set; }
public string Breed { get; set;}
}
}

This class is going to be our Model (conveniently positioned in the Models folder). Notice we have our 3 properties. We could also add some basic functions but we’ll leave it at the properties for now.

Next up is our Controller.

You should already have a “Controllers” folder if you’ve installed MVC as discussed in Part 1 but if not, go ahead and create a folder under your solution called “Controllers”.

Right click on this folder and hit Add -> Controller .

Select MVC Controller with Views…

2019-07-08_1547

On the next screen, we are going to tell the Controller which Model we want it to be tied to. In this example, we will be using the Dogs Model:

2019-07-08_1551

It will also ask for your DbContext and what you want to name the Controller. Naming convention for Controllers is [Model] + ‘s’. So, since our Model is called “Dog”, our Controller will be called “Dogs”.

And, create!

Take a minute to look around at what just got created:

  1. Brand new Controller class with several built in HTTP requests
  2. A new Views folder named after our model with 5 built in Views (Create, Edit, Delete, Details, Index)
  3. Click into one of the Views, your Model is already wired up and looks like this:
@model RescueShare.Models.Dog

Woo! Now we have used the MVC design pattern!

Now we’ll walk through how these parts interact with the user.

On our Create Dog page

2019-07-08_2123

we see our Name and Breed fields. The Controller grabs these from the Model then displays them to the View. If we remove either of those fields from the Model and refresh, the Controller will see that change and update the View.

Now, we can enter some values into the fields. Once saved, the Controller will take these values and bring them to the Model. The Model checks to see if it needs to do anything with these values and if not, stores them in the database.

Here are the 3 main files interacting on this page using MVC:

2019-07-08_2129

And there you have it! The very basics of MVC.

Web App Series

Basics of .NET Web Apps: Part 2 – PostgreSQL and Entity Framework

If you’re just jumping into this post, make sure to catch up on the current state of the RescueShare project here.

If you’ve already read up, let’s get started!

So, now we have the bare bones of a web app. But, how are we going to save and access data? We need to set up a database.

I chose to use PostgreSQL as my database based on the fact that it is powerful and is being used more frequently to handle large data. You can learn more about PostgreSQL here but the quick snapshot is that PostgreSQL is an open-sourced object-relational database that uses the SQL language. This blog series does not require experience with SQL but if you’re curious, this is a great place to get comfortable with the basics.

So, let’s download PostgreSQL!

Note: I am going to walk through the steps to download Windows x86-64 Version 11.3, but there are detailed instructions on the PostgreSQL website for other operating systems and versions.

Choose the OS and version you want to work with. I will be working with this:
2019-06-10_1831

Click through the prompts.

Make sure you install pgAdmin.

2019-06-10_1834

Okay, so now we have a pretty program and a powerful database. Cool. How do we get them to work together?

In many programs, the SQL language is how your logic will communicate with the data. However, we will be using a tool called Entity Framework to make our code cleaner and our lives a little easier.

What is Entity Framework?

TLDR: An object-relational mapper that allows you to use the what you already know and love (.NET) to communicate between your logic in Visual Studio and your data in PostgreSQL (although EF can be used with several other database providers listed here).

In-depth: Read all about Entity Framework (which I highly recommend because it’s super cool) here.

How do we get Entity Framework?

Remember the NuGet Packages we installed from Part 1? Entity Framework was one of those packages.

Why Entity Framework?

EF lets us use the Code First method which basically means we can build our database using classes rather than SQL queries. This allows us to organize our code in a more Object Oriented style and maintain a sleek and easy to-read-look.

Convinced?

Let’s get started.

First, it’s important to understand the basics of EF. There are several types in EF, most importantly being the DbContext. The DbContext communicates with Models to “write” and execute queries. Any tables you want to have in your database will be defined in the DbConext using this syntax:  

public DbSet Dogs { get; set; }
public DbSet Shelters { get; set; }
public DbSet Volunteers { get; set; }

This will look for a corresponding Model. The model is where you will define the columns for your table as properties and it looks a little like this:

namespace RescueShare.Models
{
    public class Dog
    {
        public string ID { get; set; }
        public string Name { get; set; }
        public string Breed { get; set;}
    }
}

You can find the DbContext in the Data folder in the Solution Explorer. The default name will be ApplicationDbContext.

You can add models in the Models folder by right clicking on the folder and clicking Add > Class

Remember, every time you add a new model you want to be a table, you must add it to the DbConext.

We’ll talk more later about what these Model files will contain, but for now, just add the properties you want to see as columns in your table.

Now we know how to create tables using Entity Framework. Great!

But how do we actually add them to our database?

First, let’s take a look at what our database already has.

Log in to pgAdmin if you haven’t already (this was installed with PostgreSQL and you can get to it by a quick search in your downloads folder).

Once there, navigate to localhost -> Login / Group Roles 2019-06-25_2326

Add a name to your user (I used the name of my application) and added a password under the Definition tab.

Now you have a user! This is next part could have been done with the default postgres user, however, it’s best to create your own.

Back in Visual Studio, navigate to your startup.cs file. You should see some lines of code that look similar to this

services.AddDbContext(options =&amp;amp;gt;
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores();

Currently, this is telling your application to use the default database (SQL Server) but we want to tell it to use pgAdmin. So, change the line that says

options.UseSqlServer

to say…

options.UseNpgsql

On the next line of code, you can see it is grabbing something called the “DefaultConnection”. This is found in our appsettings.json file. This also holds a default value we are going to change. Right now, you should see something that looks similar to this

"Server=(localdb)\\mssqllocaldb;Database=aspnet ..........

but we want to update it with our user we just created in pgAdmin.

Your updated version should look something like this (with your user information instead):

User ID=rescueshare;Password="";Host=localhost;Port=5432;Database=rescueshare_local;Pooling=true;

Congrats! You have now configured your application to use PostgreSQL!

Next step, getting your data actually into the database.

In the Data folder where you found the DbContext, you should have also seen a Migrations folder. A Migration is how Entity Framework wraps up all your database changes and converts them into SQL to send to PostgreSQL.

You can read more detail about Migrations in Entity Framework here

Remember the Package Manager Console from the first blog post that allowed you to add NuGet Packages? This is also where you will add migrations and update your database.

Here are the steps to adding a migration:

  1. In the Package Manger Console, run Add-Migrations

You will be prompted to add a name. This should be something short about the changes you made. After adding a name, hit enter.

You should see something like this:

2019-06-14_1301

This will automatically create a class in your Migrations folder where you can see the changes that will be made.

  1. Now that you have a migration, you need to update your database with the data.

Still in the Package Manager Console, run Update-Database.

Woo! You have just successfully moved all your database changes into your database which you can now view through pgAdmin!

That was a lot of heavy information so I highly recommend reading through some of the docs I linked throughout the post to get a deeper understanding for what we did here.

Up next, we’ll get more into the thick of it and start writing some world altering code.

Web App Series

Basics of .NET Web Apps: Part 1 – Setting up your environment

Like so many developers, I woke up one day with a great idea. The applications were endless, the creativity was flowing, and I was extremely motivated. Then, like many new developers, I opened up Visual Studio and thought now what?

This series is going to walk you through how I wrote my first API. I will share everything from resources, to missteps, to successes, and everything in between. Hopefully this will help someone else bring their ideas to life.

Let’s get started.

Day One:

I should start with talking about the motivation for writing this program.

I love dogs. Like really love dogs, and am a huge rescue advocate. Last weekend, my husband and I flew down to Atlanta (from Boston) and drove up with a 5 month old puppy that was going to be euthanized later that day. The reason we found out about this puppy was from a Facebook post my boss shared in the slack channel. This is often how rescues and potential fosters communicate, which seemed incredibly inefficient to me.

So, I started doing some research, and while I found several databases for people willing to transport, there was no real communication outside of someone having to reach out directly. It’s all unorganized and while the hearts are in the right place, I think there’s a much better way to be going about this.

The 20 hour drive from Georgia gave me plenty of time to think about how I could create something that would help shelters communicate more efficiently with each other and transport volunteers in the area. That brings us to the API. I will be writing a Web API with ASP.NET Core, Entity Framework, Razor Syntax, MVC, and Visual Studio that will create a platform for sharing open spaces in shelters, foster homes, and cars for transports.

Alright.

Let’s set up our project.

  1. Open Visual Studio and create a new project. I will be using Visual Studio 2017 but may switch sometime during this project to Visual Studio 2019 because it’s new and shiny and exciting.

  2. We’re going to start with a new ASP.NET Core Web Application

2019-06-14_1230

You can read up more about .NET here.

On the next screen, we’re going select Web Application (Model-View-Controller) as our pre loaded project template. You of course can use the blank template if you prefer, but this takes out some of the grunt work.

2019-06-14_1227

We’re also going to select the Change Authentication button. This will open up a prompt and should filled out with the following settings

2019-06-14_1228

By adding authentication, Visual Studio is going to load up Microsoft Identity that will allow us to safely create users without having to write any of the authentication algorithms ourselves.

We will be discussing Identity in later posts as we use it to build our web app but if you’re curious now, read up here

And now we have a project!

What’s next?

  1. NuGet Packages!

What the heck is NuGet Package?

TLDR: A NuGet Package is essentially a tool created and made publicly accessible by other developers so you don’t have to reinvent the wheel. We will use NuGet Packages for our frameworks and other useful tools.

You can read more deeply about NuGet Packages here.

Here is the list of NuGet Packages we will start out with (we may add more later):

Microsoft.AspNet.Mvc by Microsoft
Microsoft.AspNetCore.App by Microsoft
Microsoft.AspNetCore.Identity.EntityFrameworkCore by Microsoft
Microsoft.AspNetCore.Razor.Design by Microsoft
Microsoft.VisualStudio.Web.CodeGeneration.Design by Miscrosoft
Npgsql.EntityFrameworkCore.PostgreSQL by Shay Rojansky

We will go into more detail about what each of them do later but for now, how do we install these?

There are two ways:

First,

Visual Studio comes pre installed with a tool called “NuGet Package Manager” which does exactly what you would expect…manages NuGet Packages.

This can be accessed through Tools > NuGet Package Manager > Manage NuGet Packages for Solution…

It will look like this:

2019-06-06_1558

You can then browse, install, update, and delete packages for your solution.

Second,

The NuGet Package Manager also has a powershell pre-installed in Visual Studio where you can make all the same changes but with command line prompts. You can find a list of all the NuGet Package Powershell commands here.

Now we have a project with a bunch of pre-built tools. Great!

In Part II, we will venture into using Entity Framework to build our database.

All code for RescueShare can be found on my GitHub.