EF CodeFirst with Trusted_Connection=True does not create database - c#

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,

Related

Entity Framework - can't find/connect to localdb from within my project?

I'm following this guide:
https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
My project is named WebApplication1. I have installed Entity Framework via nuget.
I have a class called LoyaltyUsersContext.cs:
namespace WebApplication1.DAL
{
public class LoyaltyUsersContext : DbContext
{
public LoyaltyUsersContext() : base("LoyaltyUsersContext")
{
}
public DbSet<LoyaltyUser> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
I have added the following value to my in web.config:
<add name="LoyaltyUsersContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Webapplication1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
However, when I go to Server Explorer > Add Connection (MiscroSoft SQL Server, localdb doesn't show up under Server name - there aren't anything. There's also a "LoyaltyUsersContext(WebApplication1) under Data Connections, but I get an error when I try to refresh it.
Any idea why I can't seem to connect to localdb? I'm hoping it's just a connection string error or something.

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" />

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" />

Entity Framework : Change connection string at runtime

Assuming there is an ASP.NET MVC application that uses Entity Framework 6 with a code-first approach and StructureMap as IoC.
It also uses the Unit Of Work pattern.
Domain Class:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
IUnitOfWork and DbContext:
public interface IUnitOfWork
{
IDbSet<TEntity> Set<TEntity>() where TEntity : class;
int SaveChanges();
}
public class Sample07Context : DbContext, IUnitOfWork
{
public DbSet<Product> Products { set; get; }
#region IUnitOfWork Members
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
#endregion
}
Business logic in service classes :
public interface IProductService
{
void AddNewProduct(Product product);
IList<Product> GetAllProducts();
}
public class ProductService: IProductService
{
IUnitOfWork _uow;
IDbSet<Product> _products;
public ProductService(IUnitOfWork uow)
{
_uow = uow;
_products = _uow.Set<Product>();
}
public void AddNewProduct(Product product)
{
_products.Add(product);
}
public IList<Product> GetAllProducts()
{
return _products.Include(x => x.Category).ToList();
}
}
Injecting the service class in controller
public class HomeController : Controller
{
private IProductService _productService;
private IUnitOfWork _uow;
public HomeController(IUnitOfWork uow, IProductService productService)
{
_productService = productService;
_uow = uow;
}
[HttpGet]
public ActionResult Index()
{
var list = _productService.GetAllProducts();
return View(list);
}
}
StructureMap Configuration that we call in app_start :
private static void initStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.For<IUnitOfWork>().HttpContextScoped().Use(() => new Sample07Context());
x.ForRequestedType<IProductService>().TheDefaultIsConcreteType<EfProductService>();
});
//Set current Controller factory as StructureMapControllerFactory
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
Everything works fine with the single database but in my scenario user can use multiple databases, I mean the user should be able to change the connection string at runtime. We create a separate database for each project that the user creates in the application.
Now the problem is that we inject DbContext into the service and DbContext reads the connection string from the web.config so when user changes the database we cannot set a new connection string to the DbContext.
What do you suggest?
In my experience, I used the Database First mode in EF 6. The DbContext would be generated like below when I add Entity Data Model.
public TestEntities()
: base("name=TestEntities")
{
}
The TestEntities represent the ConnectionString element in the App.Config
<connectionStrings>
<add name="TestEntities" connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>
But you can change the default code to below.
public partial class TestEntities : DbContext
{
public TestEntities()
: base("name=TestEntities")
{
}
public TestEntities(string sConnectionString)
: base(sConnectionString)
{
}
...}
So you got two options to getting DB connection.
using the default. The EF will find the connection string in the config file.
passing the connection string to DbContext.
The code look like below.
EntityConnection entityConn =DBConnectionHelper.BuildConnection();
using (var db = new TestEntities(entityConn.ConnectionString))
{
....
}
As to the question How to build a EntityConnection?. Please see MSDN EntityConnection.
Hope it is helpful.
Thanks.
By default the name of the connection string to use in Entity Framework is inferred from the name of you DbContext class. However you can pass the connection string as a constructor parameter:
public class MyDbContext : DbContext, IUnitOfWork
{
public MyDbContext(string connectionString)
: base(connectionString)
{
}
}
Then you can configure StructureMap to pass in the current connection string e.g.
For<IUnitOfWork>().Use(ctx => new MyDbContext(TheConnectionStringToUse));
This could come from a static value that you set in your code, the current session etc.
I am going to suggest a completely different path. Assuming you have your connection strings set up in your web.config, which you say you do, why wouldn't you use web.debug.config and web.release.config transforrms to set your connection strings appropriately?
i.e. in web.debug.config
<connectionStrings>
<add name="FooEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=IP,PORT\Instancename;
Initial Catalog=Foo;Persist Security Info=True;User ID=admin;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>
and a web.release.config as such
<connectionStrings xdt:Transform="Replace">
<add name="FooEntities" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string="Data Source=LIVEIP,PORT\Instancename;
Initial Catalog=Foo;Persist Security Info=True;User ID=admin;Password=password;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
</connectionStrings>
A very thorough explanation is available here
public partial class YourDBContextClass
{
// Add a constructor to allow the connection string name to be changed
public YourDBContextClass(string connectionStringNameInConfig)
: base("name=" + connectionStringNameInConfig)
{
}
}
Add multiple connection strings to your web or app.config file.
in your program code:
YourDBContextClass dbcontext = new YourDBContextClass("alternateconnectionstringname");
The two approaches are good for two different situations:
The transform is good for deploying a connection string that only changes for the different evironments (test, production).
The approach of adding a constructor (which takes the connection string name) in a separate file to extend the partial dbcontext class allows the connection to be switched at runtime.
Add two different Connection String in App.Config File using different Name.
Set Current connection String Name in Entity Constructor using Overloading.
In Code File
public ASM_DBEntities()
: base("name=ASM_DBEntities")
{
}
public ASM_DBEntities(string conn)
: base("name=ASM_DBEntities1")
{
}
When we pass string with object then is use different connection string.

EF connection String Error

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; }
}

Categories