DEV Community

Cover image for Comparison between TypeORM and Entity Framework with LINQ
Yoshiaki Matsutomo
Yoshiaki Matsutomo

Posted on • Updated on

Comparison between TypeORM and Entity Framework with LINQ

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 is one of the good example frameworks.

What Entity Framework and TypeORM are

Entity Framework and TypeORM are both ORM(Object-Relational Mapping) frameworks.

What ORM is

ORM is a programming technique to query and manipulate data from data sources using an object-oriented paradigm. ORM supports developers who do not have enough knowledge about complex SQL syntaxes and DB methodology = ORM acts as a translator between the data sources and your system in your preferred languages such as Java or Python. Entity Framework and TypeORM are both open source libraries but Entity Framework is utilized in Microsoft ecosystem and TypeORM 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 attacks. However, is it perfectly blocked suspicious attacks? No, you still need the basic security knowledge even though you use ORM libraries.

Use Cases

Entity

Entity model of Entity Framework

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; }
}
Enter fullscreen mode Exit fullscreen mode

Entity model of TypeORM

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Student {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    isActive: boolean;

}
Enter fullscreen mode Exit fullscreen mode

SLECT

C# LINQ method in Entity Framework
using (var context = new CollegeDBEntities())
{    
    var student = context.Student
                  .Where(s => s.firstName == "Sam")
                  .FirstOrDefault<Student>();
}
Enter fullscreen mode Exit fullscreen mode
C# LINQ query in Entity Framework
using (var context = new CollegeDBEntities())
{
    var query = from stu in context.Student
                where stu.firstName == "Sam"
                select stu;

    var student = query.FirstOrDefault<Student>();
}
Enter fullscreen mode Exit fullscreen mode
TypeScript with TypeORM
const student = await connection
    .getRepository(Student)
    .createQueryBuilder("stu")
    .where("stu.firstName = :name", { name: "Sam" })
    .getOne();
Enter fullscreen mode Exit fullscreen mode

Generated SQL

SELECT * 
FROM Student as stu
WHERE stu.firstName = 'Sam'
LIMIT 1;
Enter fullscreen mode Exit fullscreen mode

I think that .Net developers who utilize LINQ methods often should not face any troubles in developing applications with TypeORM.

What is LINQ?
LINQ(Language-Integrated Query) is a library for the integration of query capabilities directly into the C# language and of course, it runs with Entity Framework objects. If you are familiar with SQL, LINQ queries might be easier than 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 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 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


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);
    }
}
Enter fullscreen mode Exit fullscreen mode

Seed dummy records by Entity Framework with Bogus


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);
    }
}

Enter fullscreen mode Exit fullscreen mode

Seed dummy records by TypeORM with Faker module

// 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)
  }
}
Enter fullscreen mode Exit fullscreen mode

What is Bogus and 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,

Top comments (2)

Collapse
 
mguimaraes profile image
Marcelo Guimarães da Silva

I like using TypeORM, especially with NestJS. Great library to work with typescript.

Collapse
 
muratas profile image
murat

Hi, can we use custom schema in TypeORM?