简体   繁体   中英

Fastest way to assign properties to class from datarow C#

Right now Im working in a big project, So theres a lot of data and tables going around.

For best practices Im creating a class for every table and object

Its goes like this:

public class Employee
{
    private String Name;
    public String Name
    {
        get
        {
            return Name;
        }
        set
        {
            Name = value;
        }
    }

    public Employee(int EmployeeID) 
    {
        /*
         GET DATA ROW AND ASSIGN IT TO EVERY PROPERTIE
         * 
         * Name = row("name")
         * AND DO THIS FOR EVERY PROPERTIE!
         * 
         */
    }
}

So whats happening here is that I have to assign every propertie from a query in the class constructor.

But imagine a table with like 50+ columns, I have to do this 50+ times and this takes a lot of time.

Theres a way to automate this automate the creation of the 50+ properties and the asignation of the 50+ properties in the class withouth taking a lot of time.

I just wanna find a way to create a class automating the properties assignation from a datarow instead of writting all the columns string to the properties. Something like Entityt Framework but done by me.

Greeting and thanks

There are heaps of examples online to make C# classes from dB tables & stored procedures, research that and POCO's, eg:

Generate class from database table

http://www.codeproject.com/Articles/8397/C-Code-Generator-for-Stored-Procedures

You're not the first to encounter this, best to do a quick google next time.

you should use better entity framework code first approach, it works even if your database is already created.

use a tool to generate the class model, and create a context like:

  public class MyContext : DbContext
  {
      public MyContext (){}
       public DbSet<MyModel> MyModel { get; set; }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM