Setup of mvc-mini-profiler for EF-db- first - entity-framework

I'm trying to use the mini-profiler with old-style EF code - database-first.
So far:
I've created a db context using:
string connectionString = GetConnectionString();
var connection = new EntityConnection(connectionString);
var profiledConnection = ProfiledDbConnection.Get(connection);
_context = profiledConnection.CreateObjectContext<MyEntitiesType>();
but then I hit a "Unable to find the requested .Net Framework Data Provider. It may not be installed."
which I worked around using a <system.data> reference to the MvcMiniProfiler provider:
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler" />
</DbProviderFactories>
</system.data>
but now I'm hitting a stack overflow somewhere in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbProviderServices.cs. Looking at the latest source I'm wondering if I've somehow got the setup wrong for this - if somehow my profiled connection is containing another profiled connection is containing....
Any help/advice?
Update - looking at http://code.google.com/p/mvc-mini-profiler/wiki/FrequentlyAskedQuestions at least one other person has seen the same sort of problem with 1.7 - although (s)he's doing code first. I'll keep playing to see if I can work out what to do...

Try 1.9. With the update, I just added the new Initialize method in Application_Start and removed the DbProviderFactories config section and now I have SQL profiling with EF (2 databases even, one with code first and one with database first).
protected void Application_Start()
{
....other code
MiniProfilerEF.Initialize();
}

Related

PetaPoco POCO generation fails with Sequence Contains More Then One Matching Element

PostgreSQL 9.5 Npgsql 3.1.9
I have been using PetaPoco with Npgsql to generate the POCO's with the Database.tt. All has worked well until today. After remaking the schema's in PostgreSQL, now running the Database.tt gives the error:
// This file was automatically generated by the PetaPoco T4 Template
// Do not make changes directly to this file - edit the template instead
// The following connection settings were used to generate this file
// Connection String Name: localconnection
// Provider: Npgsql
// Connection String: Server=127.0.0.1;Port=5432;Database=chaos;User
Id=postgres;password=**zapped**;Searchpath=nova
// Schema: ``
// Include Views: False
//
// Failed to read database schema - Sequence contains more than one matching element
I could find nothing in Google that address:
What does this mean (for PetaPoco), why did it happen, and how do I fix it?
TIA
Edit#1: If it helps any, in stepping through the T4 template, the _factory type
resolves to SQL Server CE --not NpgsqlFactory -- despite having the correct connection string.
_factory.GetType().Name == "SqlCeProviderFactory"
Edit#2: By rewriting LoadTables() in PetaPoco.Core.ttinclude by placing the
else if (_factory.GetType().Name == "NpgsqlFactory")
Edit#3: Now went back to PetaPoco v 5.1.211, still the same error???
The problem appears to be in LoadTables() which for Npgsql will load every table of every schema initially--even though a specific schema is listed in the searchpath, but then (why?) it zeroes out the table count before generating the tables.
Can anybody help with this??
Npgsql was installed from Nuget, as was PetaPoco.
For reference, all worked great before recreating and renaming the schemas.
The app.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<system.data>
<DbProviderFactories>
<remove invariant="Npgsql" />
<add name="Npgsql Data Provider" invariant="Npgsql" support="FF"
description=".Net Framework Data Provider for Postgresql Server"
type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<clear/>
<add name="localconnection" providerName="Npgsql"
connectionString="Server=127.0.0.1;Port=5432;Database=chaos;User Id=postgres;Password=password;Searchpath=nova"/>
</connectionStrings>
The Database.tt is set up with:
// Settings
ConnectionStringName = "localconnection"; // Uses last connection string in config if not specified
Namespace = "chaos";
RepoName = "chaosDB";
GenerateOperations = true;
GeneratePocos = true;
GenerateCommon = true;
ClassPrefix = "";
ClassSuffix = "";
TrackModifiedColumns = false;
ExplicitColumns = true;
ExcludePrefix = new string[] {}; // Exclude tables by prefix.
This is what worked, but points out some inherent problem with LoadTables() as it applies to Npgsql when the PostgreSQL database has multiple schemas--I'm guessing a name conflict somewhere..
I went back to my PostgreSQL database and dropped every schema except the one I needed. Now running the Database.tt template correctly and quickly produced the POCO's without error.
Additionally, the previous version of PetaPoco had no problem with multiple schemas--its the newest version that seems to have difficulties.

connectionString defaulting to production database.. Entity Framework

I am learning asp.net mvc 4 on top of entity framework. There is a project at work I took over and I am trying to centralize the connection credentials depending on the environment (dev, test, prod) the application is in.
Currently I have the connectionstring dynamic, but for some reason entity framework ignores the connection string initial Catalog setting.
<connectionStrings>
<add name="name1" connectionString="metadata=res://*/Model.csdl|res: //*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=001\;Initial Catalog=**;Integrated Security=False;User ID=**;Password=**;MultipleActiveResultSets=True;Application Name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="name2" connectionString="metadata=res://*/Entites.csdl|res://*/Entites.ssdl|res://*/Entites.msl;provider=System.Data.SqlClient;provider connection string="data source=001\;Persist Security Info=True;User ID=**;password=**;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I have no idea what half of the stuff in the connectionString means, but it is the second connection string giving me troubles, "name2"
Running the debugger shows the base class that extends the ObjectContext called like so,
: base("name=name2", "name2")
I figured Initial Catalog was already set in the connectionstring, "name1" and that would transfer to the name2.. but for the heck of it I added the Initial Catalog to the second connection string and it still defaults to the wrong catalog. I am connecting to the same database server but we have a test and a production database..
What could be overriding this catalog setting and redirecting to the wrong database? When I run my code, I get an innerexception telling me the username (the test database username) doesn't have access to the production database, but I am not sure why the production database is being passed in.
Here is the exception:
The server principal "testuser" is not able to access the database "ProductionName" under the current security context.]
initializing ObjectContext
public Entities() : base("name=name2", "name2")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This is also in the web.config files:
<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>
Something else interesting I noticed. When I leave the Initial Catalog setting in on the "name2" connectionstring, and set to the test database, and all the credentials are correct, I get the original error as I posted. If I change the initial Catalog to the production name and leave the wrong credentials to log in, I get a log in failed error. Same if I change the credentials around and leave the test database in for the initial catalog. So it seems it's authenticating properly, but something else is a factor once the connection goes through?
For anyone else who stumbles across this problem. I finally figured it out. The other developer was referring to the production database explicitly in all of the stored procedures. I took out all the references and left the implicit call using the "use" statement that was injected implicitly during the export/import process..
Example:
USE [TestDatabase] <---- this goes at top of procedure
Here was an explicit call to the production database:
FROM [productionDB].[dbo].[Table] table
just make it an implicit call like so:
FROM [dbo].[Table] table
If my solution is not the answer for you, I also stumbled across this bug in sql server 2008:
https://connect.microsoft.com/SQLServer/feedback/details/354291/the-server-principal-is-not-able-to-access-the-database-under-the-current-security-context-microsoft-sql-server-error-916

Use Entity Framework Code first with any database

I use SQL Server developer edition and would like to use EF code first. I found many articles explaining how to work with either a localdb or SQLExpress. How do I tell my project to rather use my ..\SQL2008 instance?
I'm thinking that somewhere, somehow, one must be able to tell the project to use a specific connectionstring. But where? Adding it to my app.config file doesn't work. This is what I've tried:
<connectionStrings>
<add name="Context" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TimeApp;Data Source=Amanda-PC\SQL2008; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can specify which connection string to use by passing the name of the connection string to the DbContext.
public class YourContext : DbContext
{
public YourContext()
: base("Context")
{
}
}
See this for more information

EF5 Code First Migration problems publishing to IIS

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.
Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

Can`t use Entity Framework - connection string not found

I am using VS2012 with .NET 4.5. I am learning Entity Framework and I have a problem. I added ADO.NET Entity Data Model to my project and generated my entities using the wizard.
The wizard added a connection string into app.config file :
<add name="MalariaEntities" connectionString="metadata=res://*/MalariaEntities.csdl|res://*/MalariaEntities.ssdl|res://*/MalariaEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=OFIR-PC;initial catalog=Malaria;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
In my project I am seeing all the entities and it seems fine but when I try to do any database action I get the following error:
No connection string named 'MalariaEntities' could be found in the application config file.
For example, I tried to insert simple row:
using (MalariaEntities DB_Context = new MalariaEntities())
{
MapsMainCategoriesDsc a = new MapsMainCategoriesDsc();
a.Category = "aa";
DB_Context.MapsMainCategoriesDsc.Add(a);
DB_Context.SaveChanges();
}
When the debugger reach to the last line the exception is raised. What can be the problem?
The wizard added a connection string so why my project cannot use it?
Thanks