Click here to Skip to main content
15,890,512 members
Articles / Programming Languages / C#
Tip/Trick

Introduction to EntityWorker

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
23 Dec 2019CPOL 3.4K   2  
EntityWorker ORM

Introduction

EntityWorker is a new ORM that I built for people who like the old way of programming as well as the new way (Entityframework).

Background

I have worked with entityframework, and loved the new way of organizing my code as well as using linq to communicate with the database.

Sadly, Entityframework is to slow, the way its build the SQL makes it too slow as well as propertychanged, memoryuseg, etc.

Entityworker addresses almost all issues the entityframework has, and also includes almost all the future Entityframework has.

Nuget

Future and Code Reviewing

Using the Code

Let's build three tables, User, Roles and Person.

C#
public abstract class Entity{
    [PrimaryKey]
    public long? Id { get; set }
}

[Table("Roles")]
public class Role: Entity{
    public string Name { get; set; }
    
    public int Level { get; set; }
}

public class UserRoles: Entity{
    [ForeignKey(typeof(User))]
    public long User_Id { get; set; }
    
    [ForeignKey(typeof(Role))]
    public long Role_Id { get; set; }
    
    [IndependentData]
    public Role Role { get; set; }
    
    public User User { get; set; }
}

public class Users: Entity{
    [DataEncode] // DataEncode will encrypt and decrypt the password
    public string Password { get; set; }
    
    // Reference to person
    public Person Person { get; set; } 
    
    // Reference to userRoles
    public List<UserRoles> UserRoles { get; set; }
}

public class Person : Entity{
    public string FullName { get; set; }
    
    public string Email { get; set; }
    
    [ForeignKey(typeof(User))]
    public long User_Id { get; set; }
}

That is all for our table, now like Entityframework, we have migrations and migrationconfig.

Let's build a migration StartUp and add an Admin Role.

C#
public class StartUp : Migration
{
    public override void ExecuteMigration(IRepository repository)
    {
        var adminUser = new User() {
            pessword= "Admin",
            UserRoles = new List<UserRoles> { Role= new Role(){ Name: "Admin" } }
            Person = new Person() {
                FullName="Alen Toma",
                Email="xxx@gmail.com"
            }        
        };
        // Now saving AdminUser will save all underclass eg Person Roles etc 
        // And all ForeignKey will be assigned automatically 
        repository.Save(adminUser);
    }
}

Now to determine which migration will be executed first, we have to create a migrationconfig.

C#
public class MigrationConfig : IMigrationConfig
{
    /// All available Migrations to be executed.
    /// trigger this class by InitializeMigration() in OnModuleStart
    public IList<Migration> GetMigrations(IRepository repository)
    {
        // return all migrations that are to be executed
        // all already executed migrations that do exist in the database will be ignored
        return new List<Migration>(){new StartUp()};
    }
}

Now that we have created our modules and migration, we need to create the Repository.

C#
// Here, we inherit from Transaction which contains the database logic for handling 
// the transaction.
// That's all we need right now.
// You will have to install the correct provider package.
// Depending on which provider you use, you will have to install System.Data.SqlClient 
// for mssql, Npgsql for pgsql and System.Data.SQLite for SQLite. 
// You will be noticed when the providers package is missing
public class Repository : Transaction
{
    // there are three databases types, mssql, Sqlite and PostgreSql
    public Repository(DataBaseTypes dbType = DataBaseTypes.Mssql) : 
    base(GetConnectionString(dbType), dbType) 
    { 
    }
    
    protected override void OnModuleStart()
    {
        if (!base.DataBaseExist())
            base.CreateDataBase();            
            
        // You could choose to use this to apply your changes to the database or 
        // create your own migration
        // that will update the database, like alter drop or create.
        // Limited support for sqlite
        // Get the latest change between the code and the database. 
        // Property Rename is not supported. renaming property x will end up removing the 
        // x and adding y so there will be dataloss
        // Adding a primary key is not supported either
        var latestChanges = GetCodeLatestChanges();
        if (latestChanges.Any())
            latestChanges.Execute(true);
            
         // Start the migration
        InitializeMigration();
    }
        
    // We could configure our modules here instead of adding attributes in the class,
    // of course, it's up to you to choose.
    // Note: This will override the attributes that exist in the class.
    protected override void OnModuleConfiguration(IModuleBuilder moduleBuilder)
    {
      
    }

    // get the full connection string
    // for postgresql make sure to have the database name lower case
    public static string GetConnectionString(DataBaseTypes dbType)
    {
      if (dbType == DataBaseTypes.Mssql)
        return  @"Server=.\SQLEXPRESS; Database=CMS; User Id=root; Password=root;";
      else if (dbType == DataBaseTypes.Sqlite)
        return  @"Data Source=D:\Projects\CMS\source\App_Data\CMS.db";
      else return "Host=localhost;Username=postgres;Password=root;Database=cms"; 
    }
}

Using Linq, you could communicate with our database now.

Simple:

C#
using ( var rep = new Repository()){

// LoadChildren its like Entityframework Include it will load all underclasses automatically
var query= rep.Get<User>().Where(x=> x.UserRoles.Any(a=> a.Role.Name == "Admin")).
           Loadchildren();
List<User> users= query.Execute();
string sql = query.ParsedSql;
}

Check out the Github for more documentation and please feel free to ask.

History

  • 23rd December, 2019: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sweden Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --