I have an ASP.NET MVC solution with EntityFramework. The DbContext and data model are in different projects.
DataModel project:
namespace DataModel
{
public class Function
{
public int FunId { get; set; }
public string Name { get; set; }
}
}
DataAccess project: with using System.Data.Entity; using DataModel;
namespace DataAccess
{
public class DbData : DbContext
{
public DbData()
: base("name=dbconn")
{
}
public DbSet<Function> functions { get; set; }
}
}
DataAccess app.config connection string:
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" >
<parameters>
<parameter value="Data Source=.; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<connectionStrings>
<add name="dbconn" providerName="System.Data.SqlClient" connectionString="Server=MYPC\SQL2012;MultipleActiveResultSets=True;Database=DBDemo;Persist Security Info=True;Integrated Security=SSPI;" />
</connectionStrings>
</configuration>
Web project references other two projects. The index page has the following code:
public ActionResult Index()
{
try
{
DbData ctx = new DbData();
ctx.SaveChanges();
}
catch (Exception e)
{
}
return View();
}
Web project wbe.config connection string
<connectionStrings>
<add name="dbconn" providerName="System.Data.SqlClient" connectionString="Server=MYPC\SQL2012;MultipleActiveResultSets=True;Database=DBDemo;Persist Security Info=True;Integrated Security=SSPI;" />
</connectionStrings>
but after running project i cannot see the database. If i check the DbContext instance ( ctx object) i see these errors:
Invalid operation. The connection is closed.
If i put DbContext class inside web project everything is ok.