在模型 class 中使用数据库是一种好方法吗?

Is it good way to work with database in model class?

我是 .Net Core 和 MongoDB 的初学者。我正在做自己的项目,Models 层中有一些对象,例如 User

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
    }
}

或者我应该将数据库和用户模型分开工作?请告诉我解决它的最佳实践方法。

我通常会创建一个数据库 class 来处理数据库。我将创建它的对象并在其他 classes 中使用它。我不确定这是不是最好的方法,但也许对你有用

数据库class是:

    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() >--------
    }
}