简体   繁体   English

ASP.net MVC 4只有1个数据库?

[英]ASP.net MVC 4 with only 1 database?

I'm using a shared database solution and I only get access to one database. 我正在使用共享数据库解决方案,但只能访问一个数据库。 How can I make my MVC application only use this 1 database for all its data? 我怎样才能使我的MVC应用程序仅使用此1数据库的所有数据? Is this possible? 这可能吗?

MVC doesn't require a database to run. MVC不需要数据库即可运行。 You can write all the code that accesses the database, so you are in complete control of how many databases it will access. 您可以编写所有访问数据库的代码,因此可以完全控制它将访问多少个数据库。

By not using any of the Microsoft-provided Membership, Session and Profile providers, which create their own database called "aspnet". 通过不使用任何Microsoft提供的Membership,Session和Profile提供程序,它们会创建自己的数据库“ aspnet”。

(Requires changes in the web.config file) (需要更改web.config文件)

Other than that, StanK is right, you can or rather have to write your code yourself. 除此之外,StanK是正确的,您可以或者必须自己编写代码。
BTW, if it isn't a Sql-Server database, you might need another ado.net provider than the one build into the .NET framework. 顺便说一句,如果它不是Sql-Server数据库,则可能需要另一个ado.net提供程序,而不是内置于.NET框架中的提供程序。

Here an example for code to access the database: 这是访问数据库的代码示例:

protected System.Data.Common.DbProviderFactory m_providerFactory = null;

 protected System.Data.SqlClient.SqlConnectionStringBuilder m_ConnectionString;



        public System.Data.Common.DbProviderFactory GetFactory()
        {
            System.Data.Common.DbProviderFactory providerFactory = null;
            providerFactory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
            return providerFactory;
        } // End Function GetFactory



 public System.Data.IDbConnection GetConnection()
        {
            System.Data.SqlClient.SqlConnection sqlc = new System.Data.SqlClient.SqlConnection("ConnectionString");

            return sqlc;
        } // End Function GetConnection



public System.Data.IDbConnection GetConnection(string strInitialCatalog)
        {
            if (string.IsNullOrEmpty(strInitialCatalog))
            {
                return GetConnection();
            }








            System.Data.SqlClient.SqlConnection sqlc = null;




            lock (this.m_ConnectionString)
            {
                string strOrigInitialCatalog = this.m_ConnectionString.InitialCatalog;
                this.m_ConnectionString.InitialCatalog = strInitialCatalog;
                sqlc = new System.Data.SqlClient.SqlConnection(this.m_ConnectionString.ConnectionString);
                this.m_ConnectionString.InitialCatalog = strOrigInitialCatalog;
                strOrigInitialCatalog = null;
            }




            return sqlc;
        }




    public override System.Data.IDbCommand CreateCommand()
    {
        return CreateCommand("");
    } // End Function CreateCommand


    public override System.Data.IDbCommand CreateCommand(string strSQL)
    {
        System.Data.IDbCommand idbc = this.m_providerFactory.CreateCommand();
        idbc.CommandText = strSQL;

        return idbc;
    } // End Function CreateCommand




public System.Data.DataTable GetDataTable(System.Data.IDbCommand cmd, string strDb)
        {
            System.Data.DataTable dt = new System.Data.DataTable();

            using (System.Data.IDbConnection idbc = GetConnection(strDb))
            {

                lock (idbc)
                {

                    lock (cmd)
                    {

                        try
                        {
                            cmd.Connection = idbc;

                            using (System.Data.Common.DbDataAdapter daQueryTable = this.m_providerFactory.CreateDataAdapter())
                            {
                                daQueryTable.SelectCommand = (System.Data.Common.DbCommand)cmd;
                                daQueryTable.Fill(dt);
                            } // End Using daQueryTable



                        } // End Try
                        catch (System.Data.Common.DbException ex)
                        {
                            //COR.Debug.MsgBox("Exception executing ExecuteInTransaction: " + ex.Message);
                            Log("cMS_SQL.GetDataTable(System.Data.IDbCommand cmd)", ex, cmd.CommandText);
                        }// End Catch
                        finally
                        {
                            if (idbc != null && idbc.State != System.Data.ConnectionState.Closed)
                                idbc.Close();
                        } // End Finally

                    } // End lock cmd

                } // End lock idbc

            } // End Using idbc

            return dt;
        } // End Function GetDataTable



public override System.Data.DataTable GetDataTable(string strSQL, string strInitialCatalog)
{
    System.Data.DataTable dt = null;

    using (System.Data.IDbCommand cmd = this.CreateCommand(strSQL))
    {
        dt = GetDataTable(cmd, strInitialCatalog);
    } // End Using cmd

    return dt;
} // End Function GetDataTable

Usage: 用法:

GetDataTable("SELECT * FROM T_User", "DB_NAME");

And code to get the provider factory for non-registered providers: 以及获取未注册提供者的提供者工厂的代码:

        public System.Data.Common.DbProviderFactory GetFactory(Type tAssemblyType)
        {
            return GetFactory(tAssemblyType.AssemblyQualifiedName);
        }


        public virtual System.Data.Common.DbProviderFactory GetFactory(string assemblyType)
        {

#if TARGET_JVM // case insensitive GetType is not supported
            Type type = Type.GetType (assemblyType, false);
#else
            Type type = Type.GetType(assemblyType, false, true);
#endif
            if (type != null && type.IsSubclassOf(typeof(System.Data.Common.DbProviderFactory)))
            {
                // Provider factories are singletons with Instance field having
                // the sole instance
                System.Reflection.FieldInfo field = type.GetField("Instance", System.Reflection.BindingFlags.Public |
                                                 System.Reflection.BindingFlags.Static);
                if (field != null)
                {
                    return (System.Data.Common.DbProviderFactory)field.GetValue(null);
                    //return field.GetValue(null) as DbProviderFactory;
                }

            }

            throw new System.Configuration.ConfigurationErrorsException("DataProvider is missing!");
            //throw new System.Configuration.ConfigurationException("DataProvider is missing!");
        } // End Function GetFactory

And an example (getting the postgre factory): 还有一个示例(获取postgre工厂):

public System.Data.Common.DbProviderFactory GetFactory()
        {
            //AddFactoryClasses();
            System.Data.Common.DbProviderFactory providerFactory = null;
            providerFactory = this.GetFactory(typeof(Npgsql.NpgsqlFactory));

            return providerFactory;
        } // End Function GetFactory

Im guessing here but are you using Entity Framework for data access and want to also make use of the Membership provider and are having trouble getting the membership schema in the same DB as your Entity Framework tables - if so try the follow: 我在这里猜测,但是您是否正在使用实体框架进行数据访问,是否还想使用成员资格提供程序,并且难以在与实体框架表相同的数据库中获取成员资格架构-如果是这样,请尝试以下操作:

Leave you're entity framework (or any other DB things youve already created exactly where they are) then specify which database you'd like to create the Membership schema in by using aspnet_regsql.exe . 离开您的实体框架(或者您已经完全创建的其他任何数据库事物),然后使用aspnet_regsql.exe指定要在其中创建成员资格架构的数据库。

This tool effectively creates the tables for you either via command line or a nice setup wizard. 该工具可以通过命令行或不错的设置向导为您有效地创建表。

See this tutorial here http://www.asp.net/web-forms/tutorials/security/membership/creating-the-membership-schema-in-sql-server-vb pay particular attention to the section entitled Step 2: Adding the SqlMembershipProvider Schema to the Database . 在此处查看本教程http://www.asp.net/web-forms/tutorials/security/membership/creating-the-membership-schema-in-sql-server-vb特别注意标题为“步骤2:添加”的部分SqlMembershipProvider模式到数据库。

Here's the important bit pasted from the above article for convenience: 为了方便起见,以下是上面文章中粘贴的重要内容:

Step 2: Adding the SqlMembershipProvider Schema to the Database 步骤2:将SqlMembershipProvider架构添加到数据库

The SqlMembershipProvider requires a particular set of tables, views, and stored procedures to be installed in the user store database. SqlMembershipProvider需要在用户存储数据库中安装一组特定的表,视图和存储过程。 These requisite database objects can be added using the aspnet_regsql.exe tool. 可以使用aspnet_regsql.exe工具添加这些必需的数据库对象。 This file is located in the %WINDIR%\\Microsoft.Net\\Framework\\v2.0.50727\\ folder. 该文件位于%WINDIR%\\ Microsoft.Net \\ Framework \\ v2.0.50727 \\文件夹中。

Note: The aspnet_regsql.exe tool offers both command line functionality and a graphical user interface. 注意:aspnet_regsql.exe工具提供命令行功能和图形用户界面。 The graphical interface is more user friendly and is what we will examine in this tutorial. 图形界面更加用户友好,这是我们在本教程中将要研究的内容。 The command line interface is useful when the addition of the SqlMembershipProvider schema needs to be automated, such as in build scripts or automated testing scenarios. 当需要自动添加SqlMembershipProvider模式时,例如在构建脚本或自动测试方案中,命令行界面很有用。

The aspnet_regsql.exe tool is used to add or remove ASP.NET application services to a specified SQL Server database. aspnet_regsql.exe工具用于向指定的SQL Server数据库添加或删除ASP.NET应用程序服务。 The ASP.NET application services encompass the schemas for the SqlMembershipProvider and SqlRoleProvider, along with the schemas for the SQL-based providers for other ASP.NET 2.0 frameworks. ASP.NET应用程序服务包含SqlMembershipProvider和SqlRoleProvider的架构,以及其他ASP.NET 2.0框架的基于SQL的提供程序的架构。 We need to provide two bits of information to the aspnet_regsql.exe tool: 我们需要为aspnet_regsql.exe工具提供两点信息:

Whether we want to add or remove application services, and The database from which to add or remove the application services schema In prompting for the database to use, the aspnet_regsql.exe tool asks us to provide the name of the server the database resides on, the security credentials for connecting to the database, and the database name. 我们是否要添加或删除应用程序服务,以及要从中添加或删除应用程序服务架构的数据库在提示数据库使用时,aspnet_regsql.exe工具要求我们提供数据库所在的服务器的名称,用于连接到数据库的安全凭据以及数据库名称。 If you are using the non-Express Edition of SQL Server, you should already know this information, as it is the same information you must provide through a connection string when working with the database through an ASP.NET web page. 如果您使用的是非Express Edition的SQL Server,则应该已经知道此信息,因为与通过ASP.NET网页使用数据库时必须通过连接字符串提供的信息相同。 Determining the server and database name when using a SQL Server 2005 Express Edition database in the App_Data folder, however, is a bit more involved. 但是,在App_Data文件夹中使用SQL Server 2005 Express Edition数据库时,确定服务器和数据库名称会涉及更多的工作。

Sorry for the newb question, guys, and thanks for all the answers! 抱歉,对于newb问题,伙计们,感谢您的所有回答! Here is what worked for me. 这对我有用。

First, Have my DBContext data model look like... 首先,让我的DBContext数据模型看起来像...

public class CDBContext : DbContext    
{
    public DbSet<tbl1> tbl1{ get; set; }
    public DbSet<tbl2> tbl2{ get; set; }
    public DbSet<tbl3> tbl3{ get; set; }
    public DbSet<tbl4> tbl4{ get; set; }
}

Then, have an example table model look like 然后,使示例表模型看起来像

public class tbl1
{
    public int ID { get; set; }

    public string Var2{ get; set; }

    public string Var3{ get; set; }
}

Next, I use the "Add->Controller" Wizard, selecting the appropriate data model (tbl1) and the appropriate context (CDBContext). 接下来,我使用“添加->控制器”向导,选择适当的数据模型(tbl1)和适当的上下文(CDBContext)。 I can then do this for model tbl2, tbl3, and tbl4! 然后,我可以为模型tbl2,tbl3和tbl4执行此操作! Each model becomes a table in the database instead of using an entire table for a database (which is what I was doing before). 每个模型都变成数据库中的一个表,而不是为数据库使用整个表(这是我之前所做的)。

It appears to work now, thanks again! 它现在似乎可以正常工作,再次感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM