I'm trying to use EF Code First with my WPF application , the idea is to create a SqlCe Db in AppData/MyApp (if there isn't one) and use it with EF Code First.
At the moment it's giving error when I try to read data off the database it supposed to create , but when I checked the db context object I saw it's trying to create it in SqlExpress.
First of all , how can I set it to work with CE instead of SqlExpress and set the file location?
I tried changing the connection string in app.config but couldn't get it to work (it didn't created sdf file) and also I'm not sure how to set connection string path to AppData folder as it's in User folder (not fixed).
Never worked with SqlCe or EF Code First before , so any help is welcome & appreciated.
Thanks in advance.
I've managed to get it working after a lot of messing around. My app.config has the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Database"
connectionString="Data Source=Database.sdf"
providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0"
invariant="System.Data.SqlServerCe.4.0"
description=".NET Framework Data Provider for Microsoft SQL Server Compact"
type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
</system.data>
</configuration>
Having the DbProviderFactory in there will help when it comes to deployment too. It will allow users to use SQLCE 4 without running the installer for it (providing you supply the native binares as well, some info here: http://erikej.blogspot.com/2011/02/using-sql-server-compact-40-with.html).
Here is a possible clue. If you were to install EFCodeFirst.SqlServerCompact using NuGet Package manager, and look in: Visual Studio 2010\Projects\MyProject\packages\EFCodeFirst.SqlServerCompact.0.8.8482\Content, it does things for your web app like:
public static class AppStart_SQLCEEntityFramework {
public static void Start() {
DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
// Sets the default database initialization code for working with Sql Server Compact databases
// Uncomment this line and replace CONTEXT_NAME with the name of your DbContext if you are
// using your DbContext to create and manage your database
//DbDatabase.SetInitializer(new CreateCeDatabaseIfNotExists<CONTEXT_NAME>());
}
}
I don't think the tooling is ready for SQLCE for WPF projects. It stopped me in my tracks too.
This probably isn't going to help in the short run, but I think it would be the best solution in the long term. I haven't been able to find where anyone else has documented how to do this so I guess I'll have to figure it out as I go unless someone with more intimate knowledge of using SqlCE4, CodeFirst, and creating NuGet packages beats me to it. What we need is a NuGet package, either a new package or make the existing one smart enough to handle it, that can add SqlCE4 and CodeFirst to a WPF and/or WinForms project.
The existing package seems geared toward web projects since it depends on WebActivator. From what I can tell, installing WebActivator on a non-web project really isn't appropriate. I don't know if it's possible for a NuGet package to detect the project type and execute different installation logic based on that information. It would be better all around for whoever is responsible for maintaining the EFCodeFirst.SqlServerCompact package to either release a non-web version or make the existing one smarter.
Pending that, in my spare time I'm going to see if I can figure out how to do it and create my own. I can't promise how long it'll take me because I'm almost totally in the dark with regards to creating NuGet packages. I've created a couple of really basic ones but have never done any advanced stuff like config transforms and the like.
Related
I have google'd the crap out of this problem, I cannot find a solution.
Using EF code first approach against a domain assembly, being consumed by a .net web application.
in the domain project there is a app.config, in there I have the following connection string for EF
<connectionStrings>
<add name="DefaultConnection" connectionString="Initial Catalog=easyDayTea;Data Source=localhost;user=sa; password=12344321" providerName="System.Data.SqlClient" />
Then in the context class TeaDb.cs I have the following constructor:
public TeaDb()
: base("name=DefaultConnection")
{
}
I have also tried just using "DefaultConnection" by itself in the constructor.
The problem:
Everything was fine until EF decided it wasn't going to take notice of additional classes/tables added to the context, so I removed EF from the project by deleting the migrations folder and empting the database of tables, then re ran enable-migrations and then the web application project to make EF do it's stuff to the database. However it did nothing!
When I run the web application though it works! and there is data (from the seed) in the tables, however not in any database i can see! It must be using a portable sql file, which doesn't make sense as I have it configured for a specific database / server by use of the configuration string.
I have also tried specifically specifying the connection string to use by doing a:
update-database -ConnectionStringName DefaultConnection -f
Still no joy.
If anyone could help me it would be amazing!
Thanks,
Xavier.
You'll find your database at Users\[youruser]\[Name you passed in your context constructor].mdf
app/web.config are only used if they are in the main project, if you have an app.config/web.config outside your main project it will not be used (some templates add them, but they are meant to be used as an example).
Check this answer for a similar problem with EF4
EF doesn't use the connection string from the app.config in the class library. It will use the connection string from the web.config in your web application. If you don't have the connection string defined in your web.config then it might be using conventions to attach the database with LocalDb in your App_Data directory.
I am trying to set up a simple ASP.NET MVC 4 webapp using DB first migrations from a SQL Server (2005). I have created the tables in the database and used Entity Framework to create the objects in the code. I can access the data using these objects.
The problems come when I try to initialize the WebSecurity using WebSecurity.InitializeDatabaseConnection("FLMREntities", "UserProfile", "UserId", "UserName", true); in the Global.asax.cs file. I have tried using the InitializeSimpleMembershipAttribute filter that came with the template and got the same issue. I get the error message:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Here is the relevant connection string:
<add name="FLMREntities"
connectionString="metadata=res://*/Models.FLMR.csdl|res://*/Models.FLMR.ssdl|res://*/Models.FLMR.msl;
provider=System.Data.SqlClient;
provider connection string="data source=notes.marietta.edu;
initial catalog=muskwater;
user id=muskwater;password=********;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
Also, I have created the membership tables in the database to match what the template creates. If I change the final parameter in the Initialize call to false (so that it does not try to create the tables automatically) it returns that it cannot find the UserProfile table. I have also tried variations on the names, such as [dbo].[UserProfile].
All I need is to have a simple account model to allow users to log in and allow certain users to see more content.
I had a similar problem, what I've done:
I modified the default connection. I already had a connection string for the edmx model, which looked like this:
<add name="ChemicalReporterEntities" connectionString="metadata=res://*/ChemicalDB.csdl|res://*/ChemicalDB.ssdl|res://*/ChemicalDB.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLExpress;initial catalog=ChemicalReporter;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
But I cannot used it with the SimpleMemebrship provider. So in Visual Studio I opened the Server Explorer > Data Connections, I selected my connection, right click, properties and I copied the connection string from there and pasted it to defaultConnection:
<add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;Initial Catalog=ChemicalReporter;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework" providerName="System.Data.SqlClient" />
After that I changed WebSecurity.InitializeDatabaseConnection to use the DefaultConnection.
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", true);
This could be a duplicate of this.
From what I remember about this problem, you need to make sure that the sqldata provider is registered. Sometimes, in your machine.config there is a duplicate entry that you need to delete and if I remember correctly, there could be an erroneous entry that you need to remove. Have a look at this msdn post, the info for this is about halfway down the page.
The link to the other SO has some links that could be helpful. If this ends up not being marked as a duplicate question, I can add them here as well or whatever is the proper thing to do.
The section you are looking for will look similar to this I think:
<system.data>
<DbProviderFactories>
<add name="SqlClient Data Provider"
invariant="System.Data.SqlClient"
description=".Net Framework Data Provider for SqlServer"
type="System.Data.SqlClient.SqlClientFactory, System.Data,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
/>
</DbProviderFactories>
</system.data>
From the information you have provided in comments, it seems that this is missing in your machine.config. Unless I am mistaken (possible) that means that the SQL Provider isn't registered on your machine. You'll need to add the above section to your web.config. You'll also need to make sure that System.Data.SqlClient is referenced in your project.
If this isn't installed on your target machine, you'll have more work to do, getting it installed. I wish I could help you with that more, but when I did this, it was for SqlServerCE, so the files I used are much different.
Good luck!
EDIT:
A critical piece of information, is the version needs to match the file that you are using. in type="blabh..blah..blah..Version=2.0.0.0, blah blah" that needs to be the version of the file you are using so right click your file and get the file version. If it fails, try variations of the version. I believe my file was 2.0.0.1 but Version=2.0 is what worked when I did it. Just try a few different versions based on your version number (2.0, 2.0.0, 2.0.0.1 for example).
Just wanted to chime in here, that I had this issue, by looking at my machine.config for the targeted .NET version that I was running off of... within the structure:
ensure that your targeted data providers are correctly inputted within there, only one per provider (I have seen duplicates cause problems), as well as, ensure that it is valid XML, and you only have one DBProviderFactories entry. In my case, I had a entry after the initial entry (essentially two entries, one with my providers, one blank), and the blank was was causing all the issues.
Hope this helps someone with the same issue :)
I have a database hosted on somee.com and I use it for my Membership, Roles and other information tables.
However, by now I only experienced minor troubles with ASPNETDB.mdf that is automatically generated by the ASP.NET Web Administration tool, so I deleted it sometimes and let the tool re-create it, so that some Roles problems will be fixed on the website.
Yesterday I didn't manage to delete it because Windows kept saying it's in use by some other application, so I simply opened the task manager and closed all SQL related tasks. Then, I managed to delete the aspnetdb file, but the tool did not re-create it!
Today I tried again and still, aspnetdb.mdf is not being generated, and also there are no SQL related tasks on task manager :(
If I can just have roles and EVERYTHING without aspnetdb.mdf, just on the somee.com database, I'll be thankful for a solution. Here are some web.config details:
<connectionStrings>
<add name="MembershipProviderDB" connectionString="workstation id=medinadb.mssql.example.com;packet size=4096;user id=user;pwd=password;data source=medinadb.mssql.example.com;persist security info=False;initial catalog=medinadb" providerName="System.Data.SqlClient"/>
</connectionStrings>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MembershipProviderDB" applicationName="AmedinaKom" enablePasswordRetrieval="false" enablePasswordReset="true" requiresUniqueEmail="true" passwordFormat="Hashed" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0"/>
</providers>
</membership>
I'm using the MembershipProviderDB for all usages, though APP_DATA/aspnetdb.mdf is still somewhat required :Z.
By the way, it seems like aspnetdb.mdf is only used for the roles. Unsure about that.
Alright I finally fixed it. I will write the solution incase anyone else is facing this problem or will in the future:
Try to add a aspnetdb.mdf from the internet and see if you face Error 26 of bad connection.
Uninstall the installed instance of Microsoft SQL Server in Control Panel -> Uninstall.
Download the installation from (http://www.microsoft.com/en-us/download/details.aspx?id=29062) and choose the version fitting your OS. (Mine is x64)
Install a server instance. Mine was SQLExpress previously.
Now enter the Administration tool and everything is like it was before.
The reason for this was closing the server through task manager. Not sure which one of the tasks was the one responsible for this, but, however - the best way is to re-install the server instance on the local machine.
I'm still looking for a way to have everything on the hosted database but I don't really care as this could be in the website's host..
The aspnetdb is for roles. If you want, like me, to have everything on the database server, learn about roleproviders (like membershipproviders) it just helped me get everything fixed.
This is a bit of a weird one. I'm doing an MVC 3 code first development using the SQL compact 4 stuff. Its all running fine but I'm getting issues when I try to scaffold a new controller. I fire up the new controller dialog and select my entity and the datacontext (both of which are in a separate assembly in the same solution) and get the following error:
Unable to retrieve metadata for 'MyNamespace.MyClassName'. Access to the database file is not allowed. [ 1884,File name=C:\Program Files\Microsoft Visual Studio 10.0\Common7\EntityContext.sdf,SeCreateFile ]
That file does not exist on disk at the moment - the EntityContext.sdf file is sat in my App_Data folder. I'm not sure if its trying to create that file (and if so why?) but if it is I'm not logged in as admin so it won't have permissions. In that case do I need to define a difference working folder or something?
I've tried it running as admin now and it works, so it's definitely trying to create a file in my Program Files directory, there must be a setting for temp files somewhere?
Any help would be great :)
Did you find an answer to the issue? I was having the same problem but handled it through the deployment transforms...
In Web.Config I used full path to the SDF:
<configuration>
<connectionStrings>
<add
name="DBContext"
connectionString="Data Source=C:\full-path\DBContext.sdf"
providerName="System.Data.SqlServerCe.4.0" />
...
In Web.Release.config I replace the connectionString attribute...
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add
name="DBContext"
connectionString="Data Source=\DBContext.sdf"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
</configuration>
After a release deploy the correct "|DataDirectory|" setting is made rather than "C:\full-path\".
I would like a fix to the original issue though!!
PK :-)
I have also faced the same problem when tried to export SQL CE db script with number of utils. Got error "Access to the database file is not allowed". Then I have just connected to that db-file from VS2010, copied connection string and... it worked! :)
I ran into this issue when using the T4Scaffolding. I got around the problem by installing the MVCScaffolding nuget package and used the "MVCScaffolding: Controller with read/write action and views, using EF data access code" template. It produces similar controller actions and views. I was unable to uninstall and reinstall the T4Scaffolding nuget package to see if this was a bug or corrupt install.
I have a very simple web part. I have a single grid view, which I am populating using linq to entities (or at least that's what I want to do). The Entity Data Model .edmx file is located in the same project as the web part, and everything looks to be in working order. When I debug the project, it blows up on the entity model constructor with the error message:
The specified named connection is
either not found in the configuration,
not intended to be used with the
EntityClient provider, or not valid.
My connection string in the App.Config is as follows:
<add name="MyDBEntities" connectionString="metadata=res://*/MyDBEntityModel.csdl|res://*/MyDBEntityModel.ssdl|res://*/MyDBEntityModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MyServer;Initial Catalog=MyDB;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
The constructor:
public MyDBEntities() : base("name=MyDBEntities", "MyDBEntities")
So, from what I've read elsewhere, my problem is that SharePoint can't see my connection string. Which means, that the App.Config from my project isn't actually getting loaded into SharePoint when I run/debug the project. If that's the case, then how I do set my project up in Visual Studio 2010 to ensure SharePoint picks up the App.Config in addition to the master SharePoint config file. If I have to manually copy the connection string, is there a "best practice" procedure for doing so? Are SharePoint Web Parts combined with the Entity Framework just not ready for prime time?
The SharePoint Tools for Visual Studio 2010 have come along way and will automatically make many of the necessary entries into web.config. Unfortunately, they won't make Entity Framework entries for you. To do this, you'll need to write a feature receiver for your web part project that adds the EF connection string.
The SharePoint API has an object named SPWebConfigModification. You should write a FeatureActivated event that uses this class to make your modification to web.config and then a FeatureDeactivating event that removes the modification.
-Greg
I was wrestling with a the same exception in a SharePoint 2010 WebPart, and I've finally got it working, but here are two important things that I learned along the way.
You must use a farm solution rather than a sandbox solution. The reason for this is, sandbox solutions do not have access to data outside the site collection. A more meaningful exception would have been helpful to solve this quickly, but I was receiving the exception as above.
Your connection string must be in the web.config of the Web Application that you install your WebPart on. It is not added automatically when you install your WebPart, so you must either update the web.config the way Greg lists above, or edit it manually. It sits in C:\inetpub\wwwroot\wss\VirtualDirectories{WebApplicationName}\web.config