Entity Framework Code First Doesn't Generate Database - entity-framework-4

I created a db Context class and added a connection string in my web.config file as instructed in Scott Guthrie's Code First Development with Entity Framework 4. I am running it from a test method. I received several database errors running the tests, but when I finally cleaned up the classes so the test succeeded, I still had no database in the App_data folder.
I added Database.CreateIfNotExists() to the dbContext constructor, but still no sdf file. Anyone know what I am doing wrong?

For the database to be automatically created, the connection string name has to be named exactly as the DbContext subclass name (with namespace).
Eg. Say your DB class is like this:
namespace MyNamespace
{
public class FooDb : DbContext
{
public DbSet<XXX> ABC{ get; set; }
}
}
Your connection string should look like so:
<connectionStrings>
<add name="MyNamespace.FooDb" connectionString="Data Source=|DataDirectory|MyNamespace.FooDb.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>

Check SQL Server Management Studio -> .\sqlexpress
That's where CF has been putting all my databases when I don't specify a connection string.

See here for auto-creating the .sdf with EF 4.1 and the SQL CE NuGet package (or a new MVC 3 project apparently):
http://www.goatly.net/2011/6/27/entity-framework-code-first-the-path-is-not-valid-check-the-directory-for-the-database.aspx
Long story short: Create an empty App_Data folder - the sdf is auto created, but only if the folder it goes in is present.

Make sure your dbcontext using correct connection string
Some thing similar like this
public class DBContext : IdentityDbContext<ApplicationUser>
{
public DBContext ()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
}
And in web.config
<add name="DefaultConnection" connectionString="Server=....;Connection Timeout=300;" providerName="System.Data.SqlClient" />

Related

Cannot connect to my edmx with my data context

I've not used VS MVC for a while but I'm writing a project which requires connecting to a Sql database which I've installed as an edmx file SwitchDB.edmx in my DAL folder. In the past I've set up my data context file which I then use to reference the data in my controller, the model help me to order the data in the correct way.
This is how my data context file looks
namespace Switches.DAL
{
public class SwitchContext : DbContext
{
public SwitchContext()
: base("DefaultConnection")
{ }
public DbSet<Switch_List> SwitchList { get; set; }
}
}
I've set up the "DefaultConnection" in my Web.config under connectionStrings and my model Switch_List.cs has the file settings. When I declare the DB context in my controller as below
private SwitchContext db = new SwitchContext();
Then I would expect to reference the SwitchContext to get my data, like this
var switches= db.SwitchList .ToList();
However, when I run the project and reference db in debug I get the following error message 'the function evaluation requires all threads to run'. The DB context SwitchContext is clearly not getting access to the Switch.edmx so what am I forgetting?
I had a similar problem, but you should see the connection properties using an IDE button (to re-evaluate the expression).
However, when you get to the part of db.SwitchList.ToList() does it generate any exceptions?

Entity Framework - Code First - Multiple projects

I have one solution with three projects in it:
ToDo.Web
ToDo.Core
ToDo.Data
ToDo.Web is my startup project and is an MVC 4 solution.
ToDo.Core is a Class Library solution and it contains all my classes like User, Task etc.
ToDo.Data is my data repository and contains my ToDoContext model.
My ToDoModel model looks like this:
namespace ToDo.Data
{
public class ToDoModel : DbContext
{
public DbSet<Task> Tasks { get; set; }
public DbSet<User> Users { get; set; }
}
}
I am trying to get the project to create my database on my locally installed SQL Server 2012. So in my web.config (in the ToDo.Web project) I have the following connectionstring:
<add name="ToDo.Data.ToDoModel" connectionString="Data Source=XXX\YYY;Integrated Security=SSPI;initial catalog=ToDo" providerName="System.Data.SqlClient" />
I then try to execute the following command from Package Manager Console:
Enable-Migrations -projectname ToDo.Data -StartUpProjectName ToDo.Web
The command executes nicely with no errors. And I can see a Migrations folder in my ToDo.Data project. But it only contains a Configuration.cs file and no information about my model. And I cannot see the database being created on my SQL server either.
I have tried creating a simple Console application, using the same connection string where it works nicely.
I have tried adding the connection string to my app.config in the ToDo.Data project without luck.
Anyone who can guide me in the right direction?

Code-first always working with SQL Server Express or SQL Server CE

I'm building a MVC 3 application and use Entity Framework 4.3 code-first. My context is becoming complex so I've decided to working with SQL Server 2008 R2. Then I changed my connection string in web.config. I checked and I know the new connection string is correct, but EF is still working with the default connection string (.\SQLEXPRESS ...) from SQL Server CE (I have now deleted SQL Server CE from nuget packages).
My context name is CodeFirstContext and my connection string name is CodeFirstContext, too. But the return context.Products; always fails and/because the connection string in context says SQLEXPRESS (my web.config sets the connection string to SQLSERVER).
What is going on here? I erased all default connection strings in the project. When I am running the project, it still gets all data from SQL Server Express.
I have been searching for about two days. Why is this so difficult if so many people only have to change the connection string and then it works.
You might be picking up the connection string from your root/machine config, in your web.config file add a clear element like so
<connectionStrings>
<clear/>
.. your connection strings here
...
I 've solved the problem like that:
public class CodeFirstContext : DbContext
{
public CodeFirstContext() : base("RandevuIzle")
{
}
public DbSet<User> Users { get; set; }
}
<connectionStrings>
<add name="RandevuIzle" connectionString="Data Source=111.222.333.444\MSSQLSERVER2008; Initial Catalog=RandevuIzle;User Id=MyUserName;Password=myPassword" providerName="System.Data.SqlClient" />
Somethings went wrong but i cannot understand. I re-start the project after doing this code below. Then it's work normally.
As you instantiate your DbContext, are you providing a name that isn't CodeFirstContext?
Holy SQL Smoke, Batman! This drove me totally batty today. Getting EF 5.0 up and running w/ VS2010 on a new project was much more difficult than I imagined. I had the same problem and found this great Ode to the Code ::
http://odetocode.com/blogs/scott/archive/2012/08/15/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx
And to be specific ::
public class DepartmentDb : DbContext
{
public DepartmentDb()
: base(#"data source=.;
initial catalog=departments;
integrated security=true")
{ }
public DbSet<Person> People { get; set; }
}
Got me the result I was needing. Do I think it's cool that I've got to set the data source like this and that it won't find the obvious solution within the app.config? No, I don't. But I have officially spent too much time attempting a transition from LINQ to SQL over to EF today and am going to go ahead and get some of the application done while I still have some interest in doing so.

Connection string for using SQL Server Compact with Entity Framework?

I'm done trying to Google for this. I have installed SQL Server CE 4.0, and have EF 4.1, but I can't get a proper connection string. Nothing on connectionstrings.com applies to me.
I just want to create a SqlCeEngine object, but no matter what I try I get some exception. Most recently it's been
Unknown connection option in connection string
with either "metadata", "app", "provider", or "provider connection string" after it. I know EF requires metadata in the connection string. And I can't imagine how anything could do without "provider connection string".
So far I have this:
<add name="DBContext"
connectionString="provider connection string="Data Source=MyDbFile.sdf;Persist Security Info=False;""
providerName="System.Data.EntityClient" />
At one point I had it with metadata:
<add name="DBContext"
connectionString="metadata=res://*/Data.DBContext.csdl|res://*/Data.DBContext.ssdl|res://*/Data.DBContext.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyDbFile.sdf;Persist Security Info=False;""
providerName="System.Data.EntityClient" />
Does it need metadata or not? What goes in the "app" part of the connection string? What should the provider be, System.Data.SqlClient or some SQL Server CE version? (which I still can't find when I try to add references. My add references window still only contains System.Data.SqlServerCe version 3.5.1.0.) Or nothing?
And what should go in the providerName attribute? Is System.Data.EntityClient correct? It's like there are 10 different variables here and every combination gives me a new equally mysterious error, none of which turns up anything useful on Google. I'm at my wits' end. Is this even possible?
You could try this in your App.config file (EF5 Code first migrations and SQL Server CE 4.0):
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlServerCe.4.0"
connectionString="Data Source=|DataDirectory|\Data\ProjectDb.sdf"/>
</connectionStrings>
And in you ProjectDb class:
class ProjectDb : DbContext
{
public ProjectDb()
: base("DefaultConnection")
{
}
}
It will work like a charm.
You can find more information here: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
I’d stuck with the same problem on Entity Framework 5.0 Code First approach with SQL Server Compact Edition 4.0
To solve it I pass instance of SqlCeConnection to DbContext's constructor:
public class Storage : DbContext
{
public Storage()
: base(new SqlCeConnection("Data Source=Database.sdf;Persist Security Info=False;"),
contextOwnsConnection: true)
{ }
//...
}
If you don’t want to inline connection string you could get it from App.config through ConfigurationManager
And of course you should add reference to the right version of System.Data.SqlServerCe (look inside Extentions tab in the Add Reference dialog)
This TechNet article outlines the steps for using EF with SQL Server Compact. This line jumped out at me, and may solve your problems:
make sure that provider=System.Data.SqlServerCe.3.5 in the connection
string.
(I would assume that you would want 4.0 instead of 3.5)
Give that a try and see how things go.
The Lu55's solution didn't work for me, but I found fow to fix it. To still use the automatic code generation (which can overwrite changes in a generated file), I added one more file with the following code:
using System.Data.Entity;
using System.Data.Objects;
namespace MyProject.Data
{
internal partial class Entities : DbContext
{
public Entities(string connectionString)
: base(
new ObjectContext(
#"metadata=res://*/Data.Model.csdl|
res://*/Data.Model.ssdl|
res://*/Data.Model.msl;
provider=System.Data.SqlServerCe.4.0;"),
true)
{
Database.Connection.ConnectionString = connectionString;
}
}
}
You have mixed a bit.
For SQL Server CE connection string can be quite easy (possibly replace DbContext with YourNameSpace.DbContextName):
<add name="DbContext"
connectionString="MyDbFile.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I also had a lot of trouble with connections, so I did the following:
installed Entity Framework for SQL Server CE
Checked that web.config contains provider with invariant System.Data.SqlServerCe.4.0
Verified that there are NO string fields (which will be represented as columns in db) with length max or mode than 4000 symbols (to add restriction use annotation [MaxLength(4000)], by default == MAX)
Metadata are necessary when you use database-first model instead of code-first, so there is .edmx file which represents generated model of the database.

EntityFramework - Where is the connection string?

I've deleted the connection string from my web.config and Entity Framework is still connecting to the database! Where is the connection string being set? This is an issue because I need to make the live version of my website point to the live database.
Here's a gotcha I found with the "convention over configuration" philosophy when it comes to trying to connect to existing databases (like you're doing).
If your DbContext class (e.g. Northwind) is in a namespace (e.g. MvcProject), for some reason EF won't match the name of the class with a connection string in web.config named "Northwind" (or "MvcProject.Northwind"), and then it will just create a connection string defaulting to the local SQLEXPRESS instance, with a database called "MvcProject.Northwind". This will be an empty database. And you'll break your head trying to figure out why you're getting no data back, until you realize that you're not connected to the right DB.
The way I got around this (not elegant but it's the quickest way I found to fix it): add a constructor to your DbContext class that calls the base with the name of the connection string in web.config - e.g.
namespace MvcProject
{
public class Northwind : DbContext
{
public Northwind() : base("Northwind") {}
}
}
Hope that helps someone out there ;-)
You'll need something like this:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Or if your database resides is App_Data folder:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|YourDatabaseFilename.mdf;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Replace MyContext with name of your class that extends DbContext.
The EF couldn´t find the connection for me but I used the connection string in the base():
namespace MvcProject
{
public class Northwind : DbContext
{
public Northwind() :
base("Data Source=servername;Initial Catalog=database;User ID=yourID;Password=yourPass;Trusted_Connection=False;") {}
}
}
Just to test the connection and it´s worked.
Convention > Configuration, right?
By default, EF Code fist will create a database in your local SQL express instance.
Look in App.Config. It will store it there too.
I faced the same problem and simply changed my connection string name as suggested in web.config file as the name of context db and all went well.
Right click on your Entity Framework mode (edmx file) > goto Properties. You'll see the connection string there.
If your Entity Model is in a separate project, then it must be in it's own settings file.
If You are using codefirst aproach with DbContext you can place a connection string with name matching your context class name in your web.config and it will work just fine.
Connection strings with Database First Approach using EntityFrameWork 5.0 This is how it looks..
<add name="DbEntities" ConnectionString="metadata=res:///Models.DbEntities.csdl|res:/// Models.DbEntities.ssdl|res://*/Models.DbEntities.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="TNS_ADMIN =( Here we write the location where tns file is located) --example of tns file location is D:\app\client\oracle\product\12.2.0\client_2\network\admin\sample;
USER ID='';PASSWORD='';DATASOURCE='';PERSIST SECURITY INFO= True"" providerName="System.Data.EntityClient"/

Resources