Basic Entity Framework C#

Reading Time: 2 minutes

In this tutorial, Basic Entity Framework C# is explained with no database, code first. To make it simple, we will prepare it as console application. We need to add reference from NuGet package.

add-reference-from-nuget-package

So, click on References folder and Manage NuGet Package.

entityframework-by-microsoft

And, if we successfully installed Entity Framework, we would be able to see it in references.

entityframework-in-references

Now, we can add some class to our project, let’s call it Person. And emphasize that this class must be public. Class Person will have ID and name. We also add virtual Department class as foreign key from the class that we will make later.

public class Person
{

public int PersonID { get; set; }

public string PersonName { get; set; }

public virtual Department Department { get; set; }

public int DepartmentID { get; set; }

}

Class Department will have ID and name also, and one virtual list of persons, since table Department will put the key in Person table.

public class Department
{

public int DepartmentID { get; set; }

public string DepartmentName { get; set; }

public virtual List<Person> Persons { get; set; }

}

Now we are ready to prepare context class, inherited from DbContext. For that purpose, we need to include namespace using System.Data.Entity;
Then, we have

class DepartmentContext : DbContext
{

public DbSet<Department> Departments { get; set;}

public DbSet<Person> Persons { get; set; }

}

Next step is utilize this classes in main program.

using (var db = new DepartmentContext())
{

Console.WriteLine(“Departments entered so far:”);

var query = from b in db.Departments

orderby b.DepartmentName

select b;

foreach (var item in query)

{

Console.WriteLine(item.DepartmentName);

}

Console.WriteLine(“Enter name of the Person:”);

var name = Console.ReadLine();

var person = new Person { DepartmentID = 1, PersonName = name };

db.Persons.Add(person);

db.SaveChanges();

var query1 = from b in db.Persons

orderby b.PersonName

select b;

Console.WriteLine(“Persons entered so far:”);

foreach (var item in query1)

{

Console.WriteLine(item.PersonName);

}

}

 

Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*