我想在ASP.NET中创建一个简单的项目,'代码优先'。代码优先 - 不创建数据库
所以我做了一个类EFDbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCRubenWouters.Models
{
public class EFDbContext: DbContext
{
public EFDbContext() : base("name=rubenwoutersdbCF")
{
Database.SetInitializer<EFDbContext>(new EFDbInitializer());
}
public DbSet<Types> Types { get; set; }
}
}
而且在 'web.config中'
<connectionStrings>
<add name="rubenwoutersdbCF" connectionString="Data Source=.\SQLSERVER2012;Initial Catalog=rubenwoutersdbCF;Integrated Security=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
然后,我创建了一个类“EFDbInitializer的东西添加到数据库中增加了一个ConnectionString的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVCRubenWouters.Models
{
public class EFDbInitializer: DropCreateDatabaseAlways<EFDbContext>
{
protected override void Seed(EFDbContext context)
{
Types t1 = new Types()
{
PK_TypeNr = 1,
TypeKeuken = "Belgisch",
TypeZaak = "Restaurant",
Vegetarisch = false
};
context.Types.Add(t1);
context.SaveChanges();
}
}
}
当我运行该项目,并转到SQL服务器管理工作室(和刷新),没有ne w数据库有..
我在这里做错了什么? :/
您是否已将Mgmt Studio连接到'。\ SQLSERVER2012'实例? – 2014-12-27 15:19:55
@marc_s是的,我做到了。 – RW24 2014-12-27 15:30:35
尝试调用实体框架,如果出现问题,您应该得到关于它的Exception。尝试调用这个:'new EFDbContext()。Types.ToList();' – Dan 2014-12-27 16:20:36