EF connection String Error - c#

My connection String in web.config file:
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
My context File
namespace EFcodefirst.Models
{
public class SampleContext: DbContext
{
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
}
My controller
SampleContext dbContext = new SampleContext();
var customerList = dbContext.Customers.ToList();
return View(customerList);
Here is the error
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
Please help me to solve this problem

Looks like you are trying to create database in same file which is used by ASP.NET membership and you don't have SQLEXPRESS installed on your machine (otherwise Entity Framework would create database with YourNamespace.SampleContext name in your SQLEXPRESS database). So, just add another connection string which will point to another database file:
<connectionStrings>
<add name="SampleContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" />
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
NOTE: If you don't want connection string to have same name as your context class, you can provide connection string name to constructor of base context class:
public class SampleContext: DbContext
{
public SampleContext()
: base("AnotherConnectionStringName")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}

Modify your dbcontext file :
public class SampleContext: DbContext
{
public SampleContext()
: base("DefaultConnection")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}

Related

EF CodeFirst with Trusted_Connection=True does not create database

Am using EF CodeFirst (Version 6.1.3) with ASP.Net MVC5 / Sql 2014 Express.
It's Entity Framework code first, setup to talk to a local sql server instance using trusted authentication, however database does not get created.
connection string in the Web.config file is
<connectionStrings>
<add name="Ppa" providerName="System.Data.EntityClient" connectionString="Server=localhost;Database=PpaOnline;Trusted_Connection=True;" />
</connectionStrings>
connection string in the App.config file of DAL layer is:
<connectionStrings>
<add name="Ppa" providerName="System.Data.EntityClient" connectionString="Server=localhost;Database=PpaOnline;Trusted_Connection=True;" />
</connectionStrings>
DbContext class is:
public class Db : DbContext
{
static Db()
{
var type = typeof(SqlProviderServices);
if (type == null)
throw new Exception("Do not remove, ensures static reference to System.Data.Entity.SqlServer");
}
public Db()
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Company> Companies { get; set; }
public DbSet<User> Users { get; set; }
}
The PpaOnlineConfiguration class is:
public class PpaOnlineConfiguration : DbConfiguration
{
public PpaOnlineConfiguration()
{
SetDefaultConnectionFactory(new SqlConnectionFactory("Server=localhost;Database=PpaOnline;Trusted_Connection=True;"));
}
}
Kindly provide input, as to where am I going wrong.
Thanks,

SQL Server connection error when checking User Roles inside a view

When i put this in my Index.cshtml:
#if (Request.IsAuthenticated && User.IsInRole("Admin"))
{
<li>Gerenciar</li>
}
It throws this error:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information:
It is not possible to connect with the SQL Server database
Everything is working SQL Server related, it creates the database, create users fine.
I already looked at other questions and there is no answer that helps!
UPDATE 1
I initialize my context using the default Identity 2.0 context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<Gatos.Models.Gato> Gato { get; set; }
public System.Data.Entity.DbSet<Gatos.Models.Formulario> Formulario { get; set; }
public System.Data.Entity.DbSet<Gatos.Models.Imagem> Imagem { get; set; }
}
My connection string:
<add name="DefaultConnection" connectionString="Data Source=Bruno-PC;Initial Catalog=Gatos;User Id = sa; Password = *******" providerName="System.Data.SqlClient" />
Update 2
Now my:
[Authorize(Roles="Admin")]
in my controllers are throwing the same error! This is driving me insane!
Are you using a custom Membership for authentication / Authorization?
As a Shortcut, try removing the following line from your main Web.Config:
<roleManager enabled="true" />
Also, take a look at the following page regarding this issue and the solution:
MVC 5 - RoleManager
Try setting your password in a connection string instead of asterisk (*)
<add name="DefaultConnection" connectionString="Data Source=Bruno-PC;Initial Catalog=Gatos;User Id = sa; Password = your_db_pwd" providerName="System.Data.SqlClient" />

set "Application.StartupPath" in may app.config connectionstring

in App.Config file :
<connectionStrings>
<add name="DB_PhonebookEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=DB_Phonebook;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
in MyModel.Designer.cs file :
namespace SimplePhoneBook
{
public partial class DB_PhonebookEntities : ObjectContext
{
public DB_PhonebookEntities() : base("name=DB_PhonebookEntities", "DB_PhonebookEntities")
{
....
}
public DB_PhonebookEntities(string connectionString): base(connectionString, "DB_PhonebookEntities")
{
....
}
public DB_PhonebookEntities(EntityConnection connection) : base(connection, "DB_PhonebookEntities")
{
....
}
....
}
How can I set Application.StartupPath into my ConnectionString?
I want create "Model" from my database thais on the applicatin path(...\debug\bin\mydatabase.mdf)
and using entities in my model!
Append this to your connection string. This will point to WebApplication1\App_Data. So your mdf file should be in App_Data folder
AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20141203171438.mdf

The type User was not mapped

I am implementing o-auth in my mvc4 web application. but when I log in using external login (Microsoft)
it gives error in my Account model.
The type User was not mapped.
my Account model is-
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection") //Exception raise here
{
}
public DbSet<User> UserProfiles { get; set; }
}
User is database generated model class. I have seen link but no help. same exception is raising every time.
my Connection string is-
<add name="DefaultConnection" connectionString="Data Source=URLofWebsite;Initial Catalog=gestest;User ID=Username;Password=Password" providerName="System.Data.SqlClient" />

Get Connection String from Method returning Connection error Object Refrence not Set to the instance of object ??? Asp.net

i am trying to get connection string from method resulting error object reference not set to the instance object my method is,
this method return connection,
namespace InspectionServices.Services
{
public class ConfigManager
{
public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["***"].ConnectionString;
}
}
}
and here i am getting connection by calling method mentioned above,
string connectionString = InspectionServices.Services.ConfigManager.GetConnectionString();
hopes for your suggestion
Thanks in Advance
EDITED:
Appconfig,
<connectionStrings>
<add name="Inspection" connectionString="Data Source=***;Database=***;Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes;" providerName="System.Data.SqlClient"/>
</connectionStrings>
You mush have web.config entries like this
<connectionStrings>
<add name="name" connectionString="***" />
</connectionStrings>
Only then you can use it in your class.
Some useful links
C# Configuration Manager . ConnectionStrings
http://www.connectionstrings.com/Articles/Show/store-connection-string-in-web-config
namespace InspectionServices.Services
{
public class ConfigManager
{
public static string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["Inspection"].ConnectionString;
}
}
}

Categories