mehrdad
mehrdad

Reputation: 356

create classes at runtime from database

How can I create classes by using database entries in runtime?

for example:

ID (int) :

1

Name (string) :

Product

Content (string) :

public class Product
{
    public string Name { get; set; }

    public string Family { get; set; }

    public int Age { get; set; }      
}

or another pattern

its for dynamic page generator


Update :

more precisely i mean i need to have a class for each record of database not a class for each table , and this class most be able to give me ability to use usual instructions of SQL like CRUD

Upvotes: 2

Views: 1919

Answers (4)

You can use JJMasterData, a library to generate CRUDs at runtime. On pull request #13, we developed C# class generation from database tables. We support both .NET 6 and .NET Framework and many features out of the box, like data importation and exportation.

Upvotes: 0

Habib
Habib

Reputation: 223247

Why do you want to create a class against database entries ? I suppose you want to create object against each entry for a class say Person. Its better that you create classes against each table and then create object against those class for records in database. I think you are looking for ORM , check Linq to SQL. Also you can create code at runtime using reflection, but I really don't see the need for it.

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062770

If you don't know about the data at compile-time, then there isn't much point building a class at runtime - you might as well use (gulp) DataTable (goes to wash hands). If you do know about the class at compile-time, then either write the class (as you have done) and use a tool like "dapper", or use an ORM tool such as EF, NHibernate, LINQ-to-SQL etc which will generate the types for you from the database (at design-time), and allow your code to interact with the type.

Upvotes: 2

cwap
cwap

Reputation: 11287

You can't really create classes dynamically (well, you can, but it's a huge anti-pattern and not something I would recommend). The way I see it, you have 2 options:

1) Using the .Net 4 dynamic keyword.

2) Create a "generic" class that contains properties holding the type, an identifier and serialized data.

Upvotes: 1

Related Questions