簡體   English   中英

如何在代碼優先實體框架中提供數據庫配置設置?

[英]How to provide database configuration settings in code-first Entity Framework?

我沒有使用localdb./sqlexpress我必須使用服務器名稱

MSOLDEV03\SQL2012

這是我生成數據庫的代碼; 當我運行時,出現SqlConnection錯誤“找不到服務器”:

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }

我用命令

 Enable-Migrations

此命令將創建遷移文件夾,但不會在我的SQL Server實例MSOLDEV03\\SQL2012上生成數據庫

然后我嘗試運行此代碼

  using (var db = new BloggingContext())
  {
            db.Blogs.Add(new Blog { Name = "Another Blog " });
            db.SaveChanges();

            foreach (var blog in db.Blogs)
            {
                Console.WriteLine(blog.Name);
            }
  }

  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();

仍未生成數據庫,但提供了與未找到的SQL Server的錯誤連接。

這是我的app.config文件不包含任何SQL連接

<entityFramework>
    <defaultConnectionFactory 
          type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="mssqllocaldb" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="System.Data.SqlClient" 
                  type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

在上下文類構造函數中,您可以提供如下鍵:

public BloggingContext() : base("name=BloggingContextKey")
        {

        }

然后在您的配置文件中為此鍵提供一個值:

<connectionStrings>
    <add name="BloggingContextKey" connectionString="Data Source=<Your server>; Initial Catalog=<Database>;user=<user>;pwd=<password>;" providerName="System.Data.SqlClient" />
  </connectionStrings>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM