首页 > 解决方案 > 在模型类中使用数据库是一种好方法吗?

问题描述

我是 .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
    }
}

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

标签: c#asp.netmongodbmodel-view-controller

解决方案


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

数据库类:

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

推荐阅读