大家好,我正在使用Entity framework 6 Code First在我的程序第一次运行时从我的模型创建一个数据库。为此,我在“Global.asax.cs”中初始化我的模型上下文但是当我运行程序时,我得到了这个错误:
初始化字符串的格式不符合从索引0开始的规范。
请帮帮我们。确实有关于此错误的堆栈溢出很多帖子,但在我读过的所有帖子中,他们都需要web.config文件中的现有连接字符串。但在我的情况下,我没有创建数据库并尝试连接到它。 我所拥有的是一个模型,并且期望EF 6在程序首次运行时创建并初始化数据库。
我在web.config中尝试了这个,但没有结果。
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
这是我的Global.asax文件:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
using (var context = new MultiTenantContext())
{
var tenants = new List<Tenant>()
{
new Tenant()
{
Id = 1,
Name = "COG",
DomainName = "www.ChurchOfGod.com",
Default = true
},
new Tenant()
{
Id = 1,
Name = "DIV",
DomainName = "www.developers.com",
Default = false
},
new Tenant()
{
Id = 3,
Name = "CW",
DomainName = "www.carwash.com",
Default = false
},
};
context.Tenants.AddRange(tenants);
context.SaveChanges();
}
}
}
这是我的模型上下文和模型类:
public class MultiTenantContext : DbContext
{
public DbSet<Tenant> Tenants { get; set; }
}
public class Tenant
{
public int Id { get; set; }
public string Name { get; set; }
public string DomainName { get; set; }
public bool Default { get; set; }
}
这是我的控制器:
public class TenantController : Controller
{
public ActionResult Index()
{
using (var context = new MultiTenantContext())
{
var tenants = context.Tenants.ToList();
return View(tenants);
}
}
}
答案 0 :(得分:2)
将模型编辑为:
pip install graphviz
将此添加到web.config&gt;配置:
namespace WebApp.Models
{
public class MultiTenantContext : DbContext
{
public MultiTenantContext() : base("DB")
{
}
public DbSet<Tenant> Tenants { get; set; }
}
}