Data Seeding in EF Core

Data seeding is a process where you populate the initial set of data into the database. I’ll explain some of the rudimentary steps needed for creating seed data in your app.

Prior to EF Core 2.1, seeding data was not quite straight-forward. However with this version, you can seed data using the following steps:

  1. Download the necessary packages from NuGet
  2. Create your Context Class
  3. Write Seed Data
  4. Run Migrations
  5. Apply data changes to your database

Let’s begin…

Download Packages: You need the following packages after you create a new .NET Core console app:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

Context Class: Create a new context class which would derive from DbContext. DbContext represents a session with the database and is used to perform CRUD operations against your database. It’s also a combination of Unit of Work and Repository patterns.

public class DataSeedContext : DbContext
    {
        public DbSet Blog { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseSqlServer(
                @"server=obi-oberoi; database=demo.DotNetConf; trusted_connection=true;");
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity()
                .Property(u => u.Url)
                .IsRequired();

            modelBuilder.Entity().HasData(
                new Blog { BlogId = 1, Url = "http://ObiOberoi.com" },
                new Blog { BlogId = 2, Url = "http://microsoft.com" },
                new Blog { BlogId = 3, Url = "http://cnn.com" },
                new Blog {  BlogId = 4, Url = "https://yahoo.com"},
                new Blog { BlogId = 5, Url = "https://tesla.com" },
                new Blog { BlogId = 6, Url = "https://meetup.com/mississauganetug"},
                new Blog { BlogId = 7, Url="https://td.com"},
                new Blog { BlogId = 8, Url="https://meetup.com/TorontoNETUG"}
                );
        }
    }

Create a Blog class like so:

public class Blog
    {
        public int BlogId { get; set; }
        [Required]
        public string Url { get; set; }
    }

Be sure to specify the type of database you wish to use. In the example, SQL Server is being used. This is defined in the Context class’s OnConfiguring method.

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseSqlServer(
                @"server=obi-oberoi; database=demo.DotNetConf; trusted_connection=true;");
        }

Run Migration: Just a quick overview of Migrations. Migrations allow you to keep your database in sync with your code. EF Core uses your mapping configurations to produce a snapshot of what your database should look like. Your model may represent tables, its primary keys, foreign keys, indexes, constraints and such.

Whenever you make a change to your POCO class i.e. add or remove a property, you ought to run a PowerShell command like so:

Add-Migration <migration name>

The Add-Migration command computes a database schema from your entity classes and scaffolds a migration with Up and Down methods which consists of the current version of the database to the new version it computes.

Apply Changes to Database: You do this by simply issuing the following command in PowerShell and you are set:

Update-Database

So, this was a quick intro to seeding data into the database.

Posted in .NET, ORM | Leave a comment

How to create an .EXE using .NET Core Console App

In the previous exercise, we learnt how to publish and execute a .NET Core Console App! In case you want to review that exercise, you can access it from here.

In this exercise, we’ll look at a quick way to turn a .DLL to an .EXE. Please note, when you build a .NET Core console app, it compiles the app to a DLL.

Here’s I’ll show you how to create an EXE:

  • Go to the command prompt and navigate to the location where the project is stored
  • Issue the following command: dotnet build -r win10-x64

You’ll find the .EXE in the folder i.e. Win10-x64. See image below:

Hope this was helpful.

Posted in .NET | Comments Off on How to create an .EXE using .NET Core Console App

How to Publish and Execute a .NET Core Console App!

Publishing a .NET Core app is as easy as 1,2,3. Here’s how:

After you have created the console app, make sure you select Release from the Solution Configurations drop-down menu.

  Now right-click on the project node inside Solution Explorer and choose Publish from the menu item. See image below:

Hit Publish, and you are set!

In order to run the app from command prompt, the quick and easy way to navigate to the location where the .dll is stored, you can do the following:

  • Open Windows Explorer
  • Navigate to the DLL file. It’ll be your project Name with a .DLL extension

  • Point your cursor to the start of your drive (see image below) and type cmd followed by space and hit Enter. This neat shortcut will take you straight to the command prompt.

  • In order to run your program, you need to type: dotnet xxx.dll where xxx is your file name

That’s it!

Happy Consoling 🙂

Posted in .NET | Tagged , | Comments Off on How to Publish and Execute a .NET Core Console App!

How to use .NET Core Console app?

Console apps have been around since .NET’s inception i.e. 2002. Over the years, it has had a bit of a windows dressing with additional APIs, integration with .NET Core and the like.

Let’s look at a simple console app written in .NET Core that simply sends an email using the Net.Mail API.

using System;
using System.Net.Mail;

namespace SMTP
{
    class Program
    {
        static void Main(string[] args)
        {
            SendTestEmail();
            Console.WriteLine("The email was sent successfully!");
            Console.ReadLine();
        }

        private static void SendTestEmail()
        {
            MailMessage mail = new MailMessage("Obi@eOberoi.com", "ooberoi@hotmail.com");
            SmtpClient client = new SmtpClient
            {
                Port = 587,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Host = "smtp.google.com",
                Credentials = new System.Net.NetworkCredential("Obi@gmail.com", "MyPassword")
            };
            
            mail.Subject = "Testing Console App!";
            mail.Body = "How is it going Obi!";
            client.Send(mail);
        }
        
    }

Links to similar blog posts (coming soon!):

Posted in .NET | Comments Off on How to use .NET Core Console app?

How to combine multiple stored procedures into a single resulset

Let’s say, you have multiple stored procedures each of which is tied to a partial view or View Component in MVC. Now, while this may seem like a logical thing to do, but what if you want the entire payload to return to a single View.

Well, how about combine all the stored procedures and return a single result set. Here’s how in three simple steps.

First, let’s take a look at the diagram below:

The Employee table has the following records:

Following are the three stored procedures that I have created for the purposes of this demo:

CREATE OR ALTER PROCEDURE [dbo].[spGetMinimumSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN
	SET NOCOUNT ON;
	 
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary BETWEEN @MinSalaryRange AND @MaxSalaryRange)
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMedianSalary]	
	@MinSalaryRange MONEY,
	@MaxSalaryRange MONEY
AS
BEGIN	
	SET NOCOUNT ON;
  
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
((Salary > @MinSalaryRange) AND (Salary <= @MaxSalaryRange))
END
CREATE OR ALTER PROCEDURE [dbo].[spGetMaximumSalary]	
	@Salary MONEY	
AS
BEGIN
	SET NOCOUNT ON;
	   
	SELECT
		FirstName, 
		LastName, 
		Gender
	FROM 
		Employee 
	WHERE
		(Salary > @Salary)
END

Now, comes the interesting part. Let's create a temporary table:

CREATE TABLE #TmpSalary 
(
	FirstName NCHAR(25),
	LastName NCHAR(25),
	Gender NCHAR(10)
)

As you can see, the temporary table only has the structure, but no data:

Select * from #TmpSalary

Now, let's insert the records into the temporary table that are returned from executing the stored procedures like so:

INSERT INTO #TmpSalary
EXEC spGetMinimumSalary 0, 50000

INSERT INTO #TmpSalary
EXEC spGetMedianSalary 50000, 75000

INSERT INTO #TmpSalary
EXEC spGetMaximumSalary 75000

Let's view the records now:

Select * from #TmpSalary

There you have it! 🙂

Posted in SQL Server | Comments Off on How to combine multiple stored procedures into a single resulset

How to pass delimited list to a Stored Procedure

Let’s write a Table-valued function below. This can be created by navigating to Functions – Table-Valued Functions inside SQL Management Studio.

Just an FYI, I am using the AdventureWorks database, but this  sample can be used in any situation.

CREATE FUNCTION [dbo].[fn_SplitStateProvinceCode]
(
   @List VARCHAR(MAX),
   @Delimiter CHAR(1)
)
RETURNS TABLE 
AS 
  RETURN ( SELECT Item = CONVERT(varchar(500), Item) FROM
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')
        FROM ( SELECT [XML] = CONVERT(XML, ''
        + REPLACE(@List, @Delimiter, '') + '').query('.')
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
      WHERE Item IS NOT NULL
  );

For testing, you can declare a variable and test the statement by passing the @List and delimiter like so. As you can see, in the sample below, the delimiter is ‘,’.

Caution: The delimited string is strictly delimited by a comma and has no space in between province codes.

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
SELECT CODES = ITEM FROM dbo.[fn_SplitStateProvinceCode (@List, ',') 

If you wish to write it in a query using the Where clause and using ‘IN’ you can do the following:

DECLARE @List VARCHAR(MAX)
SET @List = 'AB,ON,TX,VIC,WA'
Select * from Person.StateProvince 
WHERE StateProvinceCode IN (Select CODES = ITEM FROM dbo.fn_SplitStateProvinceCode (@List, ','))	

Cheers,

Obi

Posted in SQL Server | Comments Off on How to pass delimited list to a Stored Procedure

Global Query Filters in EF Core 2.0

Global Query Filters are a new addition to the arsenal of features in EF Core 2.0. This also implies that EF core team spearheaded by Diego Vega who are working diligently to bring EF Core at par with its Entity Framework 6.x classic counterpart. Like it or not, its good news for us developers, right?

Well, GQF in short are LINQ query predicates. In other words they are a boolean expression that are typically passed to the LINQ “Where” query operator and applied to Entity Types in the metadata model (usually in OnModelCreating). Such filters are automatically applied to any LINQ queries involving those Entity Types, including Entity Types referenced indirectly, such as through the use of Include or direct navigation property references.

Below is a Snapshot of the database containing two tables i.e. Department & Employee respectively.

GQFContext.cs class

namespace GlobalQueryFilters 
{
    class GQFContext : DbContext
    {
        public DbSet Department { get; set; }
        public DbSet Employee { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"server=Obi-Oberoi; database=Company; Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

    }

Department & Employee POCO Classes

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GlobalQueryFilters
{
    public class Department
    {
        [Key]
        public int DepartmentID { get; set; }
        public string Name { get; set; }
        public List Employee { get; set; }
    }

    public class Employee
    {
        [Key]
        public int ID { get; set; }
        [ForeignKey("DepartmentID")]
        public int DepartmentID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Gender { get; set; }
        public decimal Salary { get; set; }
        public bool IsDeleted { get; set; }
        public Department Department { get; set; }
    }
}

Program.cs

 
static void Main(string[] args)
        {
            using (var ctx =  new GQFContext())
            {
                var emp = ctx.Employee.ToList();

                foreach (var item in emp.Where(e => e.DepartmentID == 3))
                {
                    Console.WriteLine("Name = {0},{1}", item.FirstName, item.LastName);
                }
                Console.ReadLine();
            }
        }

Notice the two records with the DepartmentID of 3 that are being filtered using the LINQ query above.

Now, let’s try and do something different. Let’s query the records with DepartmentID of 2. In the Employee table, we have at least two records with DepartmentID of 2. See below:

Notice the record for the employee Steve Pound has one of his records marked for deletion. That’s precisely what we intended for when using Global Query Filter which as you can recall from the code snippet below. This code is defined in the GQFContext class where we have specifically filtered the record(s) that are marked for soft deletion  like so:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted);
        }

Notice, the record Steve Pound is filtered as a result of Global Query Filter that is defined as a predicate in the “HasQueryFilter” method.

Posted in ORM | Comments Off on Global Query Filters in EF Core 2.0

Difference between Varchar and Nvarchar. When to use what?

This post was replaced by an erroneous content by an intruder…I will have re-write it.

The inconvenience is regretted my dear lovely readers!

Posted in SQL Server | Leave a comment

EF Core 2.1 Roadmap

EF Core has had a makeover and continues to add new features to its arsenal.
If you have already skipped EF Core 1.0, you might want to take a look at EF Core 2.0 and see what it has to offer.

I personally like EF Core more so because it’s lightweight, sits on top of .NET standard, it’s modular, extensible and most importantly it’s cross-platform. It is also part of the .NET Core family.
If you are wondering what platform to choose when developing an application using EF Core. I’d say, just about any platform you prefer. The reason is that the APIs are no different from one platform to another. That being said, let’s dive in and explore some of the new features that EF Core brings to the table:

• Querying
• Mapping
• Performance

 

Posted in ORM | Comments Off on EF Core 2.1 Roadmap

Write a program that prints an average temperatue that is close to Zero

The idea is to get the lowest number that is close to the value zero (irrespective of the negative or positive value) from an array of average temperatures that are supplied like so:

{ 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 }

Solution:
One way is to iterate through an array of numbers and store the lowest number in a temp variable and print it out to a console.

As a side, an Array class provides methods for creating, manipulating, searching arrays which serves as the base class for all arrays in common language runtime typically referred to as CLR. The array data structure contains a contiguous collection of data items that can be accessed by an ordinal index.

I have assigned an arbitrary value of 50 to the temp variable prior to iterating through the array elements, comparing it and assigning the lowest number to the temp variable until it reaches the last element of the array before printing out the number.

public static void GetTemperatureCloseToZero()
        {
            double temp = 50.0; //some arbitrary value
            double diff;
            int target = 0;

            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };

            for (int i = 0; i < arr.Length; i++)
            {
                diff = Math.Abs(Convert.ToDouble(arr[i])) - Convert.ToDouble(target);
                if (diff <= temp)
                {
                    temp = diff;
                }
            }
            Console.WriteLine("The closest value to 0 is: {0}", temp);
            Console.ReadLine();
        }

Alternative Solution:
If you don't want to iterate through the items in an array, you can also use the Sort() method to sort elements in the entire list using the default comparer like so:

       public static void GetTempCloseToZeroSort()
        {
            double[] arr = { 7, 7.9, 10.5, -4, 3, -6, -2, 1, -15, 11.3, 9, -1 };
            List list = new List();

            foreach (var item in arr)
            {
                list.Add(Math.Abs(item));
            }
            list.Sort();
            
            Console.WriteLine("The closest value to 0 is: {0}", list[0]);
            Console.ReadLine();
        }

In both case the code produces the following output:ArrayOut1

I hope this will help those that are just getting into data structures.

Cheers,

Obi

 

Posted in Algorithms & Data Structures | Comments Off on Write a program that prints an average temperatue that is close to Zero