Home > OS >  Creating C# objects via MySQL
Creating C# objects via MySQL

Time:09-30

I would like to get help from you, please :-)

I'm thinking about good way for programmatically creating of classes in C# via MySQL database. In my app I'm creating composite classes. For example Student, Classroom, Room (dormitory) and so on. Class Student contains properties Classroom and Room. ClassRoom is also related to another entities in database...

public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Classroom Classroom { get; set; }
    public Room Room { get; set; }
}

public class Classroom
{
    public int Id { get; set; }
    public string Title { get; set; }
    public byte Level { get; set; }
    public Teacher Teacher { get; set; }
}

...etc

Usually when I need create object of some class, I must create also another classes' objects (sometime a part of database :-) ).

I think this way is not good optimalized, BUT there are great OOP benefits. When I load all students in a DataGridView, I can manage lots of related parts... for example:

Student student = ...

string currentTeacher = student.Classroom.Teacher.LastName   //... and so on.

Is OK to create all related classes' objects immediately or is better create only necessary data of current created object and another data load / create "on demand"?

Or absolutely different way? :-)

CodePudding user response:

See, the idea is for you to make a query exactly like what you need an Ingress for a structural database like sql, talking a lot about the EntityFrame mappings where it is possible to query only the student object/table only by its id, however, if no process you will need the Classroom in which it belongs to you use a .Include() no entity and you would only be able to fetch the objects you will need in your request no problem mapping all entities as a bank into objects, the problem is to retrieve all of them from the relation since it only has a feature in some articles

https://learn.microsoft.com/pt-br/ef/ef6/querying/related-data https://www.entityframeworktutorial.net/code-first/configure-entity-mappings-using-fluent-api.aspx

But if your purpose is performance, mount only the data you need in an object, just an example StudentInfo with the information you need grouped, use a Dapper to make the optimized query and make it do this mapping to your object, gaining performance

this is clear speaking of relational databases like Sql if your case is a NoSql database like MongoDb there is no problem in your mappings since it will return everything in a single document it is structured for this type of information there will be no InnerJoin cost between tables

  • Related