Accessing EF6 in code throws System.NotSupportedException in EntityFramework.dll - vb.net

based on .NET 4.0 and EF 6.1, I've created a project names Database with an Entity Model to access a SQL Server instance via Designer in Visual Studio 2013.
Additionally, there is an Console Application (also .NET 4.0) trying to consume the entities of the Database-project.
The credentials for the underlying database are stored in the Console Application's App.config within the key <connectionStrings>.
When creating a DbContext in the following way, I can perfectly access the entities:
var db = new MyEntities();
var o1 = db.Buildings.First();
MyEntities is the class that the Entity Framework creates automatically, inheriting from DbContext.
For some compatibility reasons to our guidelines, I'm trying to split up the connectionString into own keys (database, instance, user, password) within Ap.config.
For this, I'm using EntityConnectionStringBuilder to build up the EntityConnection with ProviderConnectionString, Metadata and Provider. It look's like this:
Dim sqlBuilder = New SqlConnectionStringBuilder()
sqlBuilder.MultipleActiveResultSets = True
sqlBuilder.DataSource = "database instance"
sqlBuilder.InitialCatalog = "database"
sqlBuilder.UserID = "user"
sqlBuilder.Password = "password"
Dim providerConnectionString = sqlBuilder.ToString()
Dim metaData = #"res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl"
Dim entityConnectionBuilder As New EntityConnectionStringBuilder() With { _
.Metadata = metaData, _
.ProviderConnectionString = providerConnectionString, _
.Provider = "System.Data.SqlClient"}
Dim s = entityConnectionBuilder.ToString()
entityConnection = New EntityConnection(s)
In my Console Application, I call:
var db1 = new MyEntities(entityConnection);
var o2 = db1.Buildings.First();
When executing the last line, the following exception will be thrown:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Unable to determine the DbProviderFactory type for connection of type 'System.Data.EntityClient.EntityConnection'. Make sure that the ADO.NET provider is installed or registered in the application config.
App.config of Console Application contains the following:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Any ideas, why this exception occurs?

Related

ASP.NET: I am having troubles trying to run a sql script

I have installed Microsoft SQL Server 2014 Express, and I am am learning how to use ASP.NET with Visual Studio Express 2015 for Web to retrieve data from a veterinarian database called vetDatabase_Wizard.
As a beginning, I am retrieving a protocolID from an entered ID and storing the information in a class called clinicalCase. I am 100% new to SQL.
Here is my SQLQuery1.sql script (attempt):
Select * from tblCases
CREATE PROCEDURE spGetCaseByID
#ID int
BEGIN
SELECT caseID, protocolID
FROM tblCases
WHERE caseID = #ID
END
Here is my getCaseByID function calling my SQL script:
[WebMethod]
public clinicalCase getCaseByID(int ID)
{
// Retrieve connection string
string cs = ConfigurationManager.ConnectionStrings["vetDatabase_Wizard"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetCaseByID", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#ID", ID);
cmd.Parameters.Add(parameter);
clinicalCase cases = new clinicalCase();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
cases.ID = Convert.ToInt32(reader["ID"]);
cases.protocolID = Convert.ToInt32(reader["protocolID"]);
}
return cases;
}
}
When I run the function and try it, I get the following error at
SqlDataReader reader = cmd.ExecuteReader();
Could not find the stored procedure "spGetCaseByID".
I suspect it's my SQL syntax or the fact that I added a connection string in my web.config file because I didn't have one:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="vetDatabase_Wizard"
connectionString="Data Source=JOHNATHANBO431E\SQLEXPRESS2014;Initial Catalog=vetDatabase_Wizard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
</system.webServer>
</configuration>
I got the name and connectionString from the properties panel of the database.
I would greatly appreciate the community's feedback because I must be missing something obvious! I would like to thank you very much for your time! :)
EDIT: I realized that I need to first execute my SQL script in SQL Server Management Studio before using it in Visual Studio.
However, I get the following error:
SQL80001: Incorrect syntax: 'CREATE PROCEDURE' must be the only statement in the batch. vetApp
Hence, my SQL script is wrong and would appreciate debugging help.
Your code is trying to run a SQL Server stored procedure called spGetCaseByID.
This stored procedure does not exist in your database.
you are trying to run multiple commands in SQL . In order to create stored procedure it should be the first line of code or place go in between the multiple sql command
Select * from tblCases
GO
CREATE PROCEDURE spGetCaseByID
#ID int
**AS**
BEGIN
SELECT caseID, protocolID
FROM tblCases
WHERE caseID = #ID
END
This will help

How to Manage sessions in SQL Server in Asp.net MVC

I have one solution, which has multiple projects in it, in which some
projects are developed using web form, MVC.
I need to share the session data between these projects. For this, i have
used SQLServer Mode in session state. I am able to store the session data
into database, but i am not able to retrieve the sessions data. So any
help will be appriciated.
Thanks in advance.
This is what i have tried to fetch data from ASPState database
public ActionResult Home()
{
ViewBag.Result =Session["username"].ToString();
SqlCommand cmd = new SqlCommand("select SessionId from
ASPStateTempSessions", con);
byte[] bytdata = new byte[50];
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
var list = new List<LoginUser>();
if(dr.HasRows)
{
while(dr.Read())
{
//obj=dr["SessionId"];
string obj = dr["SessionId"].ToString();
bytdata = System.Text.Encoding.UTF8.GetBytes(obj);
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytdata);
BinaryFormatter bin = new BinaryFormatter();
//bin.Serialize(ms, bytdata);
//list = (List<LoginUser>)bin.Deserialize(ms);
string session = Convert.ToString(bin.Deserialize(ms));
}
}
ViewBag.Data = list;
return View();
}
This is what i have configured ion Web.config
<sessionState mode="SQLServer" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="SessionSqlCon" cookieless="false" timeout="10" />
</providers>
</sessionState>

WebSecurity.InitializeDatabaseConnection fails with "The Role Manager feature has not been enabled." when called from console program

I have a MVC4 application using SimpleMembership to authenticate users.
I want to add users from a console program.
The console program that references a class library that has the method that will do the user creation.
It looks like this:
public class UserBuilder
{
private static readonly SimpleMembershipInitializer _membershipInitializer;
private static readonly bool _isInitialized;
private static readonly object _initializerLock = new object();
static UserBuilder()
{
LazyInitializer.EnsureInitialized(ref _membershipInitializer, ref _isInitialized, ref _initializerLock);
}
public void HandleEvent(UserAdded #event)
{
if (!WebSecurity.UserExists("ReportModels"))
{
WebSecurity.CreateUserAndAccount("ReportModels", "ReportModels");
};
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
}
}
When I start my console application I get System.Configuration.Provider.ProviderException {"The Role Manager feature has not been enabled."} at the line starting with WebSecurity.InitializeDatabaseConnection.
What do I need to do to accomplish this?
I've tried:
adding the nuget package Microsoft ASP.NET Web Pages 2 Web Data to both the console project and the class library project.
the answers listed in this post: SimpleMembershipProvider not working.
verified the connection string.
verified that the tables are in place in the database.
verified that creating users and authenticating them from the MVC4 project works.
Finally solved it thanks to information found in this blog post: http://insomniacgeek.com/to-call-this-method-the-membership-provider-property-must-be-an-instance-of-extendedmembershipprovider/ and some googling.
In essence I needed to add this to my app.config file:
<system.web>
<profile defaultProvider="SimpleProfileProvider">
<providers>
<add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"
connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager defaultProvider="SimpleRoleProvider" enabled="true">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
</system.web>
Please note the enabled="true" on the roleManager element. Without that the same exception will be thrown.

MVC 4 Creates a new database instead of using the one specified in web.config file

I have created a new MVC 4 project, Build and Run -> All Successful
Try to login -> New Database is created in SQL Express (Database name: xyz) => All good so far...
Now, I want to add a new table called "ABCD" in SQL Express (to above xyz Database). How can I access this table in Visual Studio solution? There is no Entity Framework model to go and update it manually?
However, I have added a class called ABCD in the Models folder
Created a new controller for ABCD with a new Data Context Class but when I ran the solution, it is created a new Database instead of using the default database mentioned in Web.config file
Can someone please let me know how can I fix this issue with detailed steps?
Here is my DataContext class:
using System.Data.Entity;
namespace _1024.Models
{
public class _1024Context : DbContext
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, add the following
// code to the Application_Start method in your Global.asax file.
// Note: this will destroy and re-create your database with every model change.
//
// System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<_1024.Models._1024Context>());
public _1024Context() : base("name=_1024Context")
{
}
public DbSet<ABCD> ABCDs { get; set; }
}
}
Here is the Web.config File:
<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>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-_1024-20130606134952;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />
<add name="_1024Context" connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=_1024Context-20130606135301; Integrated Security=True; MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
You should not use new connection string if you want to use existing database. In your connection strings you have two different initial catalog that means two different database.
Try to write like this without the "name=" first. This works for me.
public _1024Context() : base("_1024Context")

Move simple membership profider functionality to class library project

I'm trying to move my DbSet's to a class library project that is going to be used for database operations.
I've been following this tutorial to a Code First / SimpleMembershipProfider project. I've already got the database filled with new tables etc, via the class lib project.
But i am missing the webpages_ tables you can see on this image.
This is my datacontext class:
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
}
public DbSet<Orders> Orders { get; set; }
public DbSet<Appointment> Appointment { get; set; }
public DbSet<UserProfile> UserProfile { get; set; }
}
And for every DbSet i created a cs file. I copied the connectionString from the web.config and placed it in the app.config in the class lib project. This is how the app.config file looks like:
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I'm not sure what to do with the Filters folder (which has the class InitializeSimpleMembershipAttribute) in my webproject.
Can someone tell me how to get the webpages_ created in the database? And how to move websecurity etc to the class lib project?
Thanks in advance!
If you trying to take control of Asp.net Simple Membership Table and or Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model your Project Entity framework, there is a number of steps you need to take. I would explain them step by step but it would take too long so i will just provide you with references.
Including Asp.net Simple Membership Tables as Part of Your Entity Framework Model
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
Building Applications with ASP.NET MVC 4. You can use trial version on pluralsight
If you have any specific questions, i would be happy to answer them.