I'm trying to connect to the local database instance that visual studios provides, I setup a connection string in the appsettings.json however, it keeps failing at the integrated security keyword, it says it doesn't exist. However if I take it out, the response gets a timeout because there was no pre-authorization handshake which is because I set my dbcontext to identitydbcontext so I would need to specify the integrated security = true keyword but alas I'm stuck
This is the default connection string:
"DefaultConnection":"Server=(localdb)\\\\
mssqllocaldb;Database=ChatAppTr;MultipleActiveResultSets=true;
Integrated Security=True;"
This is how I setup the database context for my web app:
///Specify what type of user you want in identity context:
public class AppDbContext : IdentityDbContext<User>
{
public AppDbContext(DbContextOptions<AppDbContext> options) :
base( options){ }
/// Registers models to AppdbContext
public DbSet<Chat> Chats { get; set; }
public DbSet<Messages> Messages { get; set; }
}
}
I expected it to just connect to the localdb instance but nothing happened.
Related
I'm using EF Core version 2.1.11 with SQL Server Express version 12.0.2000.
I have my entity:
public class MyEntity
{
public string Id { get; set; }
public int Age { get; set; }
}
and my Db context:
public class MyContext : DbContext
{
public MyContext(DbContextOptions<MyContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>();
}
}
In order to create migrations using dotnet ef migrations add InitialCreate, I also have a design-time factory defined like:
public class MyContextFactory : IDesignTimeDbContextFactory<MyContext>
{
public MyContext CreateDbContext(string[] args)
{
var options = new DbContextOptionsBuilder<MyContext>()
.UseSqlServer("server=localhost\\SQLEXPRESS;Initial Catalog=MyTestDB;Integrated Security=true")
.Options;
return new MyContext(options);
}
}
Note that, in my SQL Express, I have not created a database named MyTestDB. I want EF Core to create this database and apply the migrations. So, my main method that attempts this is:
class Program
{
static void Main(string[] args)
{
using (var ctx = new MyContextFactory().CreateDbContext(Array.Empty<string>()))
{
ctx.Database.Migrate();
}
}
}
Now, the line ctx.Database.Migrate() raises the exception:
System.Data.SqlClient.SqlException: 'Cannot open database "MyTestDB" requested by the login. The login failed.
Login failed for user
This exception is being raised because the MyTestDB is not in SQL Express server at the time of opening the connection. What is strange is, when I run the main method, it raises this exception like 15 times (which is suppressed unless the exception settings are enabled) but when the program exits, and I check the database, the database is actually created and the migrations are applied.
My question is how can I avoid this exception being raised (I do not want to create the database before running the code)? What is the proper way to use the connection string and the Database.Migrate() method?
I have an Azure function application that when I debug it in my local PC, it won't give any error and will work correctly, but when I deploy it into the Azure Functions web, it will throw an error indicating that my Entities connection doesn't have the ProviderName specified.
I followed the solutions given by Missing ProviderName when debugging AzureFunction as well as deploying azure function, I have created a myDBContextConfig and added it to the Auto Generated dbContext file from my .edmx, but I still continue to have the same problem after deploying.
Here are some screenshots and config data I'm using:
the Error:
The local.settings.json:
{ "IsEncrypted": false,
"Values": {
//Some Values
},
"ConnectionStrings": {
"Entities": {
"ConnectionString": "metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string='data source=ES-HHASQL01\\SQLES;initial catalog=Entities;persist security info=True;Integrated Security=False;User ID=****;Password=****;MultipleActiveResultSets=True;application name=EntityFramework'",
"ProviderName": "System.Data.EntityClient"
}
}
}
And the Azure functions connection String:
The hidden connection follows the style of the quoted text below.
metadata=res:///Models.myDB.csdl|res:///Models.myDB.ssdl|res://*/Models.myDB.msl;provider=System.Data.SqlClient;provider connection string='data source=[yourdbURL];initial catalog=myDB;persist security info=True;user id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework
If any one can help me with this I would really appreciate it. Thank you.
Edit:
Well I have tested the issue with the code provided by #Joey Cai, and made the next changes:
the new App Settings connection string is has follows:
Data Source=tcp:*.database.windows.net,1433;Initial Catalog=***MultipleActiveResultSets=true;User ID=*;Password=***;Connection Timeout=30;App=EntityFramework;
I added the database configuration class to the Auto generated code from the dbContext has follows:
[DbConfigurationType(typeof(EntitiesConfig))]
public partial class Entities : DbContext
{
public Entities()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
and created the class has especified by: #Joey Cai
namespace SameHasDbContext
{
public class EntitiesConfig : DbConfiguration
{
public EntitiesConfig()
{
SetProviderServices("System.Data.EntityClient", SqlProviderServices.Instance);
SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}
}
But know I'm getting this error when running the azure function only if the connection type is SQLServer or SQLAzure, if it's set to Custom it still shows the ProviderNamer error shown before:
You can't add EF metadata about the connection in Azure Functions, as they do not use an app.config in which to specify it. This is not a part of the connection string, but is metadata about the connection besides the connection string that EF uses to map to a specific C# Class and SQL Provider etc. To avoid this, you could following the code as below.
[DbConfigurationType(typeof(DBContextConfig))]
partial class
{
public Entities(string connectionString)
: base(connectionString)
{
}
}
public class DBContextConfig : DbConfiguration
{
public DBContextConfig()
{
SetProviderServices("System.Data.EntityClient", SqlProviderServices.Instance);
SetDefaultConnectionFactory(new SqlConnectionFactory());
}
}
i have a win-form app that uses CodeFirst to work with data.
after creating database from my models i have imported records to it from another database.it works fine in my PC but when i deploy my app to another pc, codefirst tries to create new database and throws this error :
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. --->
System.Data.SqlClient.SqlException: Cannot create file
'E:\New folder (2)\Release\MyDB_log.ldf' because it already exists.
Change the file path or the file name, and retry the operation.
Could not open new database 'MyDB'. CREATE DATABASE is aborted.
Cannot attach the file 'E:\New folder (2)\Release\MyDB.mdf' as database 'MyDB'.
connection string :
<connectionStrings>
<add name="AppDbContext"
connectionString="Server=.\sqlexpress;AttachDbFilename=|DataDirectory|\MyDB.mdf;Database=MyDB;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
AppDbContext :
public class AppDbContext :DbContext
{
static AppDbContext() {
Database.SetInitializer<AppDbContext>(null);
}
public DbSet<Stock> Stocks { get; set; }
public DbSet<Report> Reports { get; set; }
}
Migration class:
internal sealed class Configuration : DbMigrationsConfiguration<Sita_Election.DAL.AppDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Sita_Election.DAL.AppDbContext";
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(Sita_Election.DAL.AppDbContext context)
{
}
}
so i want to use existing database that is created in development with codefirst,how can i do this ?
Is there any reason to have a database per application?
I would suggest using just a SQL DB if possible.
Thanks,
Phill
Your connection string is using a trusted connection so your IIS user is going to need access to that file or you could switch to a sql login. http://th2tran.blogspot.com/2009/06/underlying-provider-failed-on-open.html
I am writing an application using the VS2013 SPA template that includes Asp.NET Identity, WebAPI2, KnockoutJS and SqlServer Express 2012.
I started off using the IdentityUser class to handle my users and that worked just fine. I was able to add and login as a user with no problem. I then wanted to add custom information to the IdentityUser (there was an article I can no longer find).
As a result, I created an User class that inherited from IdentityUser as seen below.
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Then I updated all the references in the project from IdentityUser to User.
Now, whenever I try to login I get the following error:
The entity type User is not part of the model for the current context.
The thing is, I have a DBInitializer (public class ApplicationDBInitializer : DropCreateDatabaseAlways<ApplicationDBContext>) that always recreates the database and adds some test users and the tables are created and the users are added successfully.
On the off chance it matters, here is my cxn string: <add name="DefaultConnection" connectionString="Server=.\SQLEXPRESS;Database=ibcf;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
and my DBContext
public class ApplicationDBContext : IdentityDbContext<User>
{
public ApplicationDBContext()
: base("DefaultConnection")
{
}
}
Why is this error happening?
The issue was that the Startup.Auth.cs continued to reference the default IdentityDbContext<User> DB context. After updating the class to reference my ApplicationDBContext the issue was resolved.
static Startup()
{
...
UserManagerFactory = () => new UserManager<User>(new UserStore<User>(new ApplicationDBContext()));
...
}
I've spent a while on this now and have only found a workaround solution that I'd rather not do...
I have a context as shown below. Is there a programmatic way to specify the database to connect to via the constructor, and get it to use the System.Data.SQLite entity framework provider to connect to a SQLite database? This is working via the app.config (with a connectionstring called "Context"), but not via any programmatic way I can find of supplying it. I have tried using an entity connectionstring builder and that produces the following string:
provider=System.Data.SQLite;provider connection string='data
source="datafile.db"'
When the context is first queried with this string I get a message "Keyword not supported: 'provider'."
public class Context : DbContext
{
public IDbSet<Test> Tests { get; set; }
public Context()
: base("Context")
{
}
}
*Edit.
I may have solved this by implementing my own connectionfactory:
public class ConnectionFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string nameOrConnectionString)
{
return new SQLiteConnection(nameOrConnectionString);
}
}
Then setting:
Database.DefaultConnectionFactory = new ConnectionFactory();
However, it seems like there should be a built in way to do this, and also one that does not involve overriding the global default connection factory.