I'm testing how code first works. Here's how I defined the Context
public class EfDbContext: Context
{
public DbSet<Client> Clients { get; set; }
}
I didn't create any data base, but I was able to do all the CRUD operations.
Now I don't see the connection string in my web.config. I don't see either the Database. I've checked the App_Data Directory and also the Sql Server Express. I don't see any trace of the Database created.
Yet, everything is perfectly.
EF code-first will use a connection string that has the same name as your DB context - so you could define it like this:
<connectionString>
<add name="EfDbContext"
connectionString="server=YourServer;database=YourChoice;Integrated Security=SSPI;" />
</connectionString>
The database won't be created by default, until you actually do something, e.g. it should show up as soon as you make a call to EfDbContext.SaveChanges() for the first time.
It will be called the same as your DB context (YourNamespace.EfDbContext) if you haven't defined your own, custom connection string, and it should show up in your default local SQL instance.
See from the ADO.NET EF 4.1 Code First Walkthrough:
Where’s My Data?
DbContext by convention created a database for you on
localhost\SQLEXPRESS. The database is named after the fully qualified
name of your derived context, in our case that is
“CodeFirstSample.ProductContext”. We’ll look at ways to change this
later in the walkthrough.
Related
I want to create ASP.NET MVC app using database on Azure. I have already written model classes for database. But how can attach this database or tables on azure?? It's connections string for my already created DB, which i want to use.
<add name="AccomodationContext" connectionString="Server=tcp:student-docs.database.windows.net,1433;Database=docDb;User ID={username};Password={password};Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
It's empty, I would like to use it to has a tables created from my model classes, or create a new database. But I can't find, how should look correct connection string. I know that for LocalDB there is 'AttachDbFilename' in connection string.
You should have a connection called DefaultConnection in your web.config that you can place your connections string in.
You can get the actual connection string directly from your Azure portal.
I am creating dynamic connection strings in my project. They're created on the fly with the information provided specifically for every user. When the application first fires off, if a database doesn't exist (first time user logs on), a new database is created without problems with this initializer:
public DataContext() : base()
{
// ProxyCreation and LazyLoading doesn't affect the situation so
// comments may be removed
//this.Configuration.LazyLoadingEnabled = false;
//this.Configuration.ProxyCreationEnabled = false;
string conStr = GetDb();
this.Database.Connection.ConnectionString = conStr;
}
The problem is, with this method, I have to restart the application pool on the server and the new user should be the first accessor to the application.
I need the same thing without a requirement of restarting the app. Is that possible?
(This is a SPA using AngularJS on MVC views and WebApi as data provider - May be relevant somehow, so thought I should mention)
I already tried this, but this creates an error for EF and the application doesn't start at all...
You could try a little bit different approach to connect directly (and create) the right database.
public class DataContext : DbContext
{
public DataContext(DbConnection connection) : base(connection, true) { }
}
Here you create the DbContext already with the right connection.
Take also care because you need to specify to migrations that the right connection should be used (not the Web.Config connection but the connection that raised the database creation).
See the second overload here https://msdn.microsoft.com/en-US/library/hh829099(v=vs.113).aspx#M:System.Data.Entity.MigrateDatabaseToLatestVersion.
I am going through ASP.NET MVC 3 tutorial. Got to the point where EnityFramework was used for model classes. I ran the the application without having connection strings in the web.config specified and it worked.
I could add, edit, delete records. And the weirdest thing is that they are sill there even after I stop development server and start debugging application again as if table was created somewhere in memory and stayed alive for some reason. Can anybody explain what was going on?
Here's a link to an image:
oi48.tinypic.com/fnbeba.jpg
Was it supposed to use the the connection string for which name matches the name of the class derived from DbContext?
EDIT1:
Because I had no connection string in web.config it was generated by Enity Framework using namespace and the name of the class derived from DBContext. By default EF uses SQL Express, hence database file was created in database server's DATA direcotry C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA.
The last thing I don't understand why it wouldn't create the database file in App_Data dir if DBContext derived class is
public class MoviesDBContex : DbContext
{
public DbSet<Movie> Movies { get; set; }
// Passing name of the connections string shouldn't be even necessary
public MoviesDBContex()
: base("MoviesDBContex")
{ }
}
and web.config contains
<connectionStrings>
<add name="MoviesDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlClient"/>
</connectionStrings>
Thist what the Microsoft guide about ER connections and models (msdn.microsoft.com/en-us/data/jj592674.aspx) says:
If the name of the connection string matches the name of your context (either with or without namespace qualification) then it will be found by DbContext when the parameterless constructor is used. If the connection string name is different from the name of your context then you can tell DbContext to use this connection in Code First mode by passing the connection string name to the DbContext constructor.
Any idea why database file isn't created in App_Data?
EDIT2:
There was a missing 't' in the class name and hence it didn't match the name of the connection string.
I does work as expected when provider is SQL Server Compact providerName="System.Data.SqlServerCe.4.0", but if I change it to providerName="System.Data.SqlClient" I get an exception added below. Shouldn't regular SQL Server be able to create a database file also?
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Do you have SQL Express installed on your machine? Which version of Entity Framework are you using? As long as I know the Entity Framework targets the local SQL Express as its default connection string if no string connection is provided.
I believe it is using SQL Server express, writing the DB files to the app_data directory within your application.
This is called "Convention over configuration", and Entity Framework and MVC use this principle a lot. Basically, it says that unless you give it specific instructions otherwise, they will assume various conventions.
If you don't supply a connection string to EF, then it will use a default connection string, generated from the namespeace and name of the class. If that doesn't exist in your web.config, then it will use the DefaultConnection that is defined in the machine.config located in the folder tree at C:\Windows\Microsoft.NET
I have written a trivial Entities code-first WinForms application with one simple class and one database context class as all the tuturials describe it.
But I did not add a connection string in the app.config file.
Nevertheless, when I start the application, it can insert objects into the database and even show all objects already inserted.
I figure there must be some default database in SQL Server for that case but I cannot find out which instance and database name is used.
Database name is the same as the name on your DbContext class. By default it creates a database on the local machine Sql Server express installation. You should be able to see it in Sql Server Managment when you connect to your local SQLEXPRESS.
If you spesify a connectionstring with the same name as youd DbContext it will use that instead.
I am having a real problem, I created multiple users in sql server with different dbroles, and now im trying to check what's the user role in db and connect to a connection string depending on their role as this will be more secure..... how can I choose between different connection strings and pass it to the model.edmx, remember I am working with 3 tier design.
here is how my login control works:
http://i40.tinypic.com/nvz6lt.jpg
here is my connectionclass:
http://i39.tinypic.com/34qmybs.jpg
here is my app.config file:
http://i43.tinypic.com/6xq4q8.jpg
Thanks alot
There are multiple overloads for the ObjectContext constructor.
The default one just takes the connectionstring with a matching name from the config file. But you can also use a constructor where you specify the connection string yourself.
In your code you could maybe create a Authorization enum with values like BasicUser, Admin and pas that to your ConnectionClass. There you could do a switch and pick the right connection string from your config.