Reputation: 741
Good day guys, I am using Entity framework 6 Code First to create a database from my model when my program first runs. To do this I initialize my model context in "Global.asax.cs" But when ever I run the program I get this error:
Format of the initialization string does not conform to specification starting at index 0.
Please help me guys. It is true that there tons of post on stack overflow concerning this error, but of all the posts that I have read they all need an existing connection string in web.config file. But in my case I don't have a database created already and trying to connect to it. What I do have is a model existing and expecting EF 6 to create a and initialize the database when the program first run.
I have tried this in web.config, but no result.
<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>
Here is my Global.asax file:
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();
}
}
}
Here is my model context and model class:
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; }
}
Here is my controller:
public class TenantController : Controller
{
public ActionResult Index()
{
using (var context = new MultiTenantContext())
{
var tenants = context.Tenants.ToList();
return View(tenants);
}
}
}
Upvotes: 1
Views: 14139
Reputation: 2294
Edit your model to:
namespace WebApp.Models
{
public class MultiTenantContext : DbContext
{
public MultiTenantContext() : base("DB")
{
}
public DbSet<Tenant> Tenants { get; set; }
}
}
Add this to web.config > configuration:
<connectionStrings>
<add name="DB" connectionString="data source=.\sqlExpress;initial catalog=XXX;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
Upvotes: 4