无法使用实体框架代码创建数据库

时间:2015-11-14 20:32:18

标签: c# .net entity-framework ef-code-first

我尝试在Windows窗体应用程序中使用Entity Framework代码优先在SQL Server中创建数据库。该程序运行没有错误,但我无法在我的SQL Server中看到任何数据库。为什么呢?

我创建了2个类

public class Country :System.Object
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Country()
    {

    }

    public Country(int id, string name)
    {
            this.Id = id;
            this.Name = name;
    }
}

class DataBaseContext : System.Data.Entity.DbContext
{
    public DataBaseContext()
        : base("connectionStringName")
    {

    }

    public System.Data.Entity.DbSet<Country> countries { get; set; }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Models.DataBaseContext ODB = null;

        try
        {
            ODB = new Models.DataBaseContext();
            Models.Country OCountries = new Models.Country();
            OCountries.Id = 1;
            OCountries.Name="AA";
            ODB.countries.Add(OCountries);
            ODB.SaveChanges();
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
        finally   
        {
            if (ODB != null)
            {
                 ODB.Dispose();
                 ODB = null;
            }
        }
    }
}

app.config是:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>

<section name="entityFramework"             type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<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>
</configuration>

1 个答案:

答案 0 :(得分:1)

根据您的连接字符串,将在localdb中创建数据库。

您可以打开Sql Server Management Studio并更改&#34;服务器名称&#34;到(localdb)\mssqllocaldb和&#34;身份验证&#34;到&#34; Windows身份验证&#34;并登录到系统上安装的本地数据库实例。在那里,您可以找到由Entity Framework创建的数据库。

另请注意,.NET具有统一的对象模型,这意味着您不需要从中派生一个类,因此将public class Country :System.Object更改为public class Country

相关问题