我目前正在创建Windows窗体应用程序。我需要一个本地数据库,并选择使用实体框架的代码优先方法来构建它。我之前不使用C#与数据库合作,我正在努力设置实体框架。
我目前有两个课程:Ingredient
和Recipe
。两者都含有POCO。根据我的收集,实体框架应该创建一个本地数据库,使这些类表成为可能。但是,没有创建数据库。
有人能说清楚我做错了吗?如果我的问题太宽泛,我道歉。
感谢您的时间。
Ingredient
上课:
public class Ingredient
{
public int IngredientID { get; set; }
public string IngredientName { get; set; }
public string IngredientDescription { get; set; }
public virtual Recipe Recipe { get; set; }
}
Recipe
上课:
public class Recipe
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public string RecpeDescription { get; set; }
public virtual List<Ingredient> Ingredients { get; set; }
public Recipe()
{
this.Ingredients = new List<Ingredient>();
}
}
DbContext
班级
class RecipeContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Ingredient> Ingredients { get; set; }
}
答案 0 :(得分:2)
EF对这些事情非常灵活。熟悉Nuget包管理器控制台(您可以从那里与Entity Framework数据库生成例程进行交互)。按照这些步骤,你应该很高兴:
在启动应用程序中添加连接字符串。一个例子如下:
<configuration>
<connectionStrings>
<add name="Local"
connectionString=
"Data Source=.;Initial Catalog=NAME;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
创建一个继承DbContex;
将以下构造函数添加到Context类:
public Context() : base("Local") {}
将DbSet属性添加到Context类中(以便EF可以跟踪它们);
转到程序包管理器控制台,选择包含DbContext类的项目,然后键入以下内容:
Enable-Migrations
在同一控制台类型上:
Add-Migration Initial
再次在同一个控制台中:
Update-Database
这应该创建一个数据库,其中包含您在连接字符串中设置的名称。
希望这有帮助!
干杯!
答案 1 :(得分:0)
如果数据库不存在,则需要一个连接字符串和一个创建数据库的数据库初始化程序。
public class RecipeContext : DbContext
{
// the default constructor
public RecipeContext() : base() { }
// this one lets you pass a connection string
public RecipeContext( string connectionString ) : base( connectionString ) { }
...
然后,在应用程序的最开始设置初始化程序:
Database.SetInitializer<RecipeContext>(new CreateDatabaseIfNotExists<RecipeContext>());
最后,尝试使用有效的连接字符串连接到您的数据库:
// local database connection string has to point to the local db server
string cs = "server=(localdb)/v11.0;database=anewdatabase;integrated security=true";
using ( var ctx = new RecipeContext( cs ) )
{
// any database operation will first trigger the initializer
// which initializes the database once per app domain
// in case of the CreateDatabaseIfNotExists
// a new, empty database matching your model is created
}