Yann Thibodeau
Yann Thibodeau

Reputation: 1261

How to implement an ORM in C#

I am trying to implement my own ORM in C# for MySQL as the one I have found are not able to do exactly what I want.

I currently have implemented only a few methods (eg save method):

public void Save()
    {
        string queryVariables = "";
        foreach (PropertyInfo propertyInfo in this.GetType().GetProperties().Where(x => x.Name != "BdClass" && x.GetValue(this) != null))
        {
            string isLast = this.GetType().GetProperties().Last() == propertyInfo ? "" : ", ";
            queryVariables += $"{propertyInfo.Name} = '{MySqlHelper.EscapeString(propertyInfo.GetValue(this).ToString())}'{isLast}";
        }
        ConnectionSingleton.Query($"INSERT INTO {this.GetType().GetProperties().Single(x => x.Name == "BdClass").GetValue(this)} SET {queryVariables} ON DUPLICATE KEY UPDATE {queryVariables};");
    }

I am trying to implement the FindAll() method which I want it to return me a List with the type of the object calling the function. Let's say I have a class called Person and I want to get all the rows of the Person table from the database, I want to write it this way:

List<Person> persons = Person.FindAll();

I am struggling with the creation of the object in the FindAll() method.

Upvotes: 0

Views: 4121

Answers (2)

Carles Vallejo
Carles Vallejo

Reputation: 11

I prefer to use NEntityDb. It supports MySQL and other databases such as SQL Server, Oracle, PostgreSQL, IBM Db2 MariaDB, Sqlite or Firebird.

With NEntityDb for MySQL you can query and save data to the database with .NET LINQ Expressions and Fluent API.

Upvotes: 0

billybob
billybob

Reputation: 2998

Take a look at Insight Db. We are using it to handle Sql Server, Oracle and DB2. It supports MySQL also. I find it really easy to use and saves a lot of time.

Upvotes: 1

Related Questions