c# - 在模型类中使用数据库是一种好方法吗?
问题描述
我是 .Net Core 和 MongoDB 的初学者。我正在开发自己的项目,模型层中有一些对象,例如,用户
Class User {
[BsonElement("name")]
string name;
[BsonElement("email")]
string email;
// other fields...
}
问题是:我应该在用户模型中使用数据库吗?
Class User {
[BsonElement("name")]
string name;
[BsonElement("email")]
string email;
// other fields...
void saveToDatabase() {
//some implementation to save object in database
}
}
或者我应该分开使用数据库和用户模型?请告诉我解决它的最佳实践方法。
解决方案
我通常创建一个处理数据库工作的数据库类。我将创建它的一个对象并在其他类中使用它。我不确定这是否是最好的方法,但也许对你有用
数据库类:
public static class clsDB
{
//-------------------< Class: DB >-------------------
public static SqlConnection Get_DB_Connection()
{
//--------< db_Get_Connection() >--------
//< db oeffnen >
string cn_String = Properties.Settings.Default.connection_string;
SqlConnection cn_connection = new SqlConnection(cn_String);
if (cn_connection.State != ConnectionState.Open) cn_connection.Open();
//</ db oeffnen >
//< output >
return cn_connection;
//</ output >
//--------</ db_Get_Connection() >--------
}
public static DataTable Get_DataTable(string SQL_Text)
{
//--------< db_Get_DataTable() >--------
SqlConnection cn_connection = Get_DB_Connection();
//< get Table >
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(SQL_Text, cn_connection);
adapter.Fill(table);
return table;
}
public static void Execute_SQL(string SQL_Text)
{
//--------< Execute_SQL() >--------
SqlConnection cn_connection = Get_DB_Connection();
//< get Table >
SqlCommand cmd_Command = new SqlCommand(SQL_Text, cn_connection);
cmd_Command.ExecuteNonQuery();
}
public static void Close_DB_Connection()
{
//--------< Close_DB_Connection() >--------
string cn_String = Properties.Settings.Default.connection_string;
SqlConnection cn_connection = new SqlConnection(cn_String);
if (cn_connection.State != ConnectionState.Closed) cn_connection.Close();
//--------</ Close_DB_Connection() >--------
}
}
推荐阅读
- android - 如何在从活动中单击按钮时使复选框在 RecyclerView 中可见?
- python - 多个 Pandas 列表列,希望为每个列表元素展开并创建一行
- asp.net-core - 类型安全的 `a` 标记助手
- php - 获取 singleValueExtendedProperties
- encoding - 字符的编码是否取决于字体的字体样式
- java - Java 表示法 - 印刷。
toSysOut().withLabel("源流") - c# - 如何使用 Dapper 将 DateTime 传递给存储过程?
- xml - 在 Oracle 10g 上加载超过 64K 的 XML
- gnuplot - 绘制多个文件以产生多个输出
- javascript - 将多个图像复制/粘贴到 ClipboardData(剪贴板 API)