Best Practice with classes and the database

2019-08-22 03:45发布

问题:

I would like to learn more about the appropriate way to use classes when using a database. Here is the example of what I think is ok.(Using C# and SQL Server if curious)

I Have a table called "Features" and most of the columns in it hold IDs(Foreign keys). To load that table into the application, I create a "DBFeatures" class to hold all the columns. Next I should have a regular "Features" class that has the actual values of all properties in "DBFeatures" class. "Features" class would have a method that opens a connection to the database to grab all the right values with the given IDs. Then The "Features" class can be used as is.

The same would go in reverse, I create an object of "Features", then it converts it into a "DBFeatures" class which gets passed to the database when INSERTING.

Is this the right way to go about this? What other options would be better? The only other option is just have one class, "DBFeature" class, and when I create an object of that class, each time a property is set or gets, it would have to access the database to get the value by providing an ID.

EDIT

I'll be using the data for forms. Most of the tables will be read only which will be stored into a list of objects which can then be used with Controls(like the data source of a combobox). Also I want to be able to load user input into a class that would be outputed to a table in the database.

回答1:

A lot of planning on how to do something depends on your implementation which you are not providing. What are you planning to do with your objects? Is it for a report? Do you need to manipulate the values?

I'm going to assume you are going to be manipulating the data in which case you should have a class that opens the database and loads it into classes that represent it.

The class can have properties that correspond to the columns and then you can have a list of the class to represent the rows.

This is just one example of how to do it but its impossible to say without knowing what your intent is and having more details.



回答2:

It looks like you need ORM like Entity Framework.