繁体   English   中英

无法先使用Entity Framework代码创建数据库

[英]Can't create database with Entity Framework 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>

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

您可以打开Sql Server Management Studio,将“服务器名称”更改为(localdb)\\mssqllocaldb ,将“身份验证”更改为“ Windows身份验证”,然后登录到系统上安装的本地数据库实例。 在这里,您可以找到由实体框架创建的数据库。

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

暂无
暂无

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

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