将数据库指定为DbContext [英] specify Database to DbContext

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

问题描述

我先使用Entity Framework Code,并使用连接字符串创建DbContext。如果连接字符串未指定初始目录,则可以通过某种方式将DbContext配置为使用服务器上的特定数据库(而无需在连接字符串上设置初始目录)

I am using Entity Framework Code First and am creating a DbContext using a connection string. If the connection string does not specify an Initial Catalog, is there some way I can configure the DbContext to use a specific database on the server (without setting the Initial Catalog on the connection string)

我在派生的DbContext类的OnModelCreating事件中查看了modelBuilder可用的配置选项,但没有任何提示。显然,如果我在连接字符串上设置了初始目录,一切都会按我希望的那样工作。

I looked at the configuration options available off of modelBuilder in the OnModelCreating event in my derived DbContext class, but nothing jumped out at me. Obviously, if I set the initial catalog on the connection string things work as I want them to.

推荐答案

您可以选择名称这样的数据库:

You could choose the name of the DB like this:

public class MyDataContext : DbContext {
    public MyDataContext() : base("MyDatabaseName") 
    {
        Database.DefaultConnectionFactory = new SqlConnectionFactory(myConnectionString);
    }
}

这篇关于将数据库指定为DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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