类和数据库的最佳实践 [英] Best Practice with classes and the database

查看:61
本文介绍了类和数据库的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想详细了解使用数据库时使用类的适当方法。这是我认为可以的示例。(如果好奇,请使用C#和SQL Server)

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)

我有一个名为功能的表,其中的大多数列保留ID(外键)。为了将该表加载到应用程序中,我创建了一个 DBFeatures类来保存所有列。接下来,我应该有一个常规的 Features类,该类具有 DBFeatures类中所有属性的实际值。 功能类将具有一种方法,该方法打开与数据库的连接,以获取具有给定ID的所有正确值。然后可以按原样使用功能类。

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.

相反,我创建了一个功能对象,然后将其转换为插入时会传递给数据库的 DBFeatures类。

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.

这是解决此问题的正确方法吗?还有什么其他选择会更好?唯一的另一选择是只有一个类 DBFeature,当我创建该类的对象时,每次设置或获取属性时,它都必须访问数据库以通过提供ID来获取值。

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.

编辑

我将使用表格数据。大多数表将是只读的,并将被存储到对象列表中,然后可以与Controls一起使用(例如组合框的数据源)。我还希望能够将用户输入加载到一个类中,该类将输出到数据库中的表。

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.

推荐答案

A关于如何做某事的大量计划取决于您未提供的实现。您打算如何处理对象?是要举报吗?您需要操纵值吗?

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.

这篇关于类和数据库的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆