Comparison between TypeORM and Entity Framework with LINQ
Tags: csharp, dotnet, typescript, database
Published: 2021-03-17 06:29:03

---
title:Comparison between TypeORM and Entity Framework with LINQ
description: The article explains the difference between TypeORM and Entity Framework with LINQ
series: TypeORM
tags: csharp, dotnet, typescript, database
---

##Introduction
I was a .Net developer and am a Node.js/Typescript developer at the moment. Of course, I faced many differences such as the coding style, development environment and principles etc. On the other hand, I also found some similarities to the Microsoft ecosystem. This topic, [TypeORM](https://typeorm.io/#/) is one of the good example frameworks. 

###What Entity Framework and TypeORM are
[Entity Framework](https://docs.microsoft.com/en-us/ef/) and [TypeORM](https://typeorm.io/#/) are both [ORM(Object-Relational Mapping)](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) frameworks.

###What ORM is
[ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) is a programming technique to query and manipulate data from data sources using an object-oriented paradigm. [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) supports developers who do not have enough knowledge about complex SQL syntaxes and DB methodology = [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) acts as a translator between the data sources and your system in your preferred languages such as Java or Python. [Entity Framework](https://docs.microsoft.com/en-us/ef/) and [TypeORM](https://typeorm.io/#/) are both open source libraries but [Entity Framework](https://docs.microsoft.com/en-us/ef/) is utilized in Microsoft ecosystem and [TypeORM](https://typeorm.io/#/) is specialized for a JS/Node.js environment.

###Why We Use
* Code First -> In the Code-First approach, we can focus on the domain of our application and start creating classes for our domain entity rather than 'DB First' (= design our DB first and then create the classes which match our DB design).
* Flexibility -> It provides the concept of DB abstraction which makes us switch/migrate DB itself and data easily, and maintain the consistent code for our applications.
* Safer -> They basically use placeholders for setting parameters = It reduces the risk of [SQL injection](https://www.w3schools.com/sql/sql_injection.asp) attacks. However, is it perfectly blocked suspicious attacks? **No, you still need the basic security knowledge even though you use [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) libraries**. 

##Use Cases

###Entity

####Entity model of Entity Framework
```C#
using System.ComponentModel.DataAnnotations;

public class Student
{
    [Key]
    public int id { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
    public boolean isActive { get; set; }
}
```

####Entity model of TypeORM
```TypeScript
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Student {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    isActive: boolean;

}
```

###SLECT 

#####C# LINQ method in Entity Framework
```C#
using (var context = new CollegeDBEntities())
{    
    var student = context.Student
                  .Where(s => s.firstName == "Sam")
                  .FirstOrDefault<Student>();
}
```

#####C# LINQ query in Entity Framework
```C#
using (var context = new CollegeDBEntities())
{
    var query = from stu in context.Student
                where stu.firstName == "Sam"
                select stu;
   
    var student = query.FirstOrDefault<Student>();
}
```

#####TypeScript with TypeORM
```TypeScript
const student = await connection
    .getRepository(Student)
    .createQueryBuilder("stu")
    .where("stu.firstName = :name", { name: "Sam" })
    .getOne();
```

####Generated SQL
```SQL
SELECT * 
FROM Student as stu
WHERE stu.firstName = 'Sam'
LIMIT 1;
```

I think that .Net developers who utilize [LINQ](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) methods often should not face any troubles in developing applications with [TypeORM](https://typeorm.io/#/).

>What is LINQ?
[LINQ(Language-Integrated Query)](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) is a library for the integration of query capabilities directly into the C# language and of course, it runs with [Entity Framework](https://docs.microsoft.com/en-us/ef/) objects. If you are familiar with SQL, [LINQ](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) queries might be easier than [LINQ](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) methods.

##Benefits
I mentioned some benefits in the section 'Why We Use'. I want to share some actual cases.

###Migration
How do you effectively update your schema and the related existing functions? When we have already had data in our DB and the related functions such as stored procedures, indexes and triggers etc., it could be a big job because you might refresh your tables/objects and re-create them = you might lose the data and the other DB objects. Both [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) frameworks provide migration tools that automatically update the schema/objects when our models change without losing the existing data and any related DB objects.

###Data seed
How do you insert the data into your DB during the developing/testing phases? Without [ORM](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping) frameworks, we might need to execute SQLs to insert some test data. Both of them seed the data to our DB during the DB initialization processes. 

####Seed your original records by [Entity Framework](https://docs.microsoft.com/en-us/ef/)
```C#

DropCreateDatabaseAlways<CollegeDBContext>
{
    protected override void Seed(CollegeDBContext context)
    {
        IList<Student> studentList = new List<Student>();

        studentList.Add(new Student() { firstName = "Sam", lastname = "Smith" });
        studentList.Add(new Student() { firstName = "James", lastname = "Williams" });
        studentList.Add(new Student() { firstName = "Lisa", lastname = "Adams" });

        context.Student.AddRange(studentList);
        base.Seed(context);
    }
}
```

####Seed dummy records by [Entity Framework](https://docs.microsoft.com/en-us/ef/) with [Bogus](https://github.com/bchavez/Bogus)
```C#

DropCreateDatabaseAlways<CollegeDBContext>
{
    protected override void Seed(CollegeDBContext context)
    {
        var testStudents = new Faker<Student>()
        .RuleFor(s => s.firstName, f => f.Name.FirstName(f.PickRandom<Gender>()))
        .RuleFor(s => u.lastName, f => f.Name.LastName(f.PickRandom<Gender>()));

        var studentList = testStudents.Generate(5);

        context.Student.AddRange(studentList);
        base.Seed(context);
    }
}

```

####Seed dummy records by [TypeORM](https://typeorm.io/#/) with [Faker](https://www.npmjs.com/package/faker) module 
```TypeScript
// Student.factory.ts
define(Student, (faker: typeof Faker) => {
  const gender = faker.random.number(1);
  const firstName = faker.name.firstName(gender);
  const lastName = faker.name.lastName(gender);
 
  const student = new Student();
  student.firstName = firstName;
  student.lastName = lastName;
  return student
})

// CreateStudent.seed.ts
export default class CreateStudents implements Seeder {
  public async run(factory: Factory, connection: Connection): Promise<any> {
    await factory(Student)().createMany(5)
  }
}
```
>What is [Bogus](https://github.com/bchavez/Bogus) and [Faker](https://www.npmjs.com/package/faker)?
They are libraries randomly to create a variety of dummy data such as human name, address, date and product/company name etc. = reduce our boring time of generating dummy records and have testing cases with multiple dummy values instead of our static ones.

##Concolusion
The programing language barrier is an obstacle for new developers who change languages like natural language,  Japanese vs English. Moreover, as you know, the lifecycle of advanced technology/framework/theory is rapidly changed. The two factors would negatively influence our motivation. However, the direction would be the same in any languages because they are invented to achieve the same goal = effective/safe/beautiful development processes and products themselves. 

##What Next is
I will publish more details of my learning obtained from my individual investigation and work in commercial development.          

##Bio
When I was 30 years old, I went to Australia for changing my career on a Working Holiday visa. I graduated from University of Sydney with a Bachelor of Computer Science and Technology. During the period, I also worked as a Fraud Prevention Analyst at Amex in Sydney, Australia (yes, it was super busy. I went to my uni during the day and worked at night...) 

After graduation, I worked as a C#/.Net developer for an Australian small business for 5 years. Now, I came back to Japan and work as a TypeScript/Go/React developer for a Japanese security start-up company. 

I love learning new fields which is a big challenge. I am happy if you support me to accelerate the improvement of my skill/knowledge. Please feel free to contact me if you are interested in my unique career.

Thanks,