Entity Framework 4 + SQL Server CE + Generate database from model - entity-framework

The title sums up my problem. I start from an empty model in VS2010 beta2, and then choose to generate my database from model, i then choose to create a new SQL CE database. Up until that moment everything runs fine. EF generates some SQL and saves it as MyModel.emdx.sql. Here comes the problem, the generated SQL can't be executed on the CE database and throws a couple error messages, like 'ALTER TABLE is not supported' and some others.
I reckon there is no way to do Model first with an SQL CE database, so I'm back to the Database first approach. Or has anyone managed to sucessfully generate an SQL CE database from the edmx model in VS2010?

I just ran a MyModel.edmx.sql script against an SQL CE database and it executed without error. I used VS 2010 RC, so I suspect the problem you encountered was related to the Beta 2 release. I conclude that the problem was fixed in the RC

When you first Generate Database from Model..., you will create a connection in App.Config. If you initially created a non-CE connection, you will generate non-CE SQL, and it will get a .sql extension as you described (if your connection is to CE, you will get a .sqlce extension on the DDL file).
You need to delete the connectionstring from App.Config, and maybe the datasource from Project -> Properties -> DataSources. Then when you choose Generate Database from Model... it will ask to create a new connection, and you can choose a CE connection instead of a server one.

Related

Entity Framework not returns data

I'm using EntityFramework 6.1.3. I have generated models from an existing database. Now, when trying to query the database, datacontext returns null. The database appears to be empty.
But the database is not empty as I can connect and query it using LINQPad. When googling the problem I came across a similar situation. In that case the EF generated an empty database on the local server and the solution was to tweak the connection string, although without clear details what exactly should be changed.
However, I'm not sure if that is the case in my situation.
My connection string is pointing to the remote server.
It is not possible that the database was created on the remote server, as we don't have authorisation.
The database was not created on my local machine as I dont even have local sql server installed. And my AppData folder is empty.
Any suggestions?
Generated connection string below
<add name="MAST_DEV" connectionString="metadata=res://*/Models.Mast_DevModel.csdl|res://*/Models.Mast_DevModel.ssdl|res://*/Models.Mast_DevModel.msl;provider=System.Data.SqlClient;provider connection string="data source=xxxxxx;initial catalog=MASTER_DEV;user id=xxxxx;password=xxxxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I don't really know what I was doing wrong. I have created simple project from scratch , generated models again and it does work fine now. Possibly, previously I selected 'Code first from the database' from Entity Data Model Wizard. Whereas this time 'EF Designer from the database'. Anyway, thanks for trying to help. It was my mistake
This is the exact solution for my problem (the answer is copied from here Entity Framework cant use the DbContext, model being created)
"I see you are using the EDMX with Templates (.tt) for generating the classes. But if you are getting the information from a existing database, the wizard will create a ConnectionString compatible with ObjectContext (metadata informations and provider of entityframework).
The problem is that the connectionstring you are using is for ObjectContext (Database First and Model First). For the DbContext you should use the connectionstring without the metadata informations"

Accessing DB2-LUW 10 with entity framework 6

I am developing an application in which the database is selected by the end user at runtime. The database can either be on a MS SQL server or an IBM DB2 server. I am currently using IBM DB2 10 Express-c on a windows server for testing. I am developing using Visual Studio 2013 C# and Entity Framework 6. I have installed the EntityFramework.IBM.DB2 Nuget package for the DB2 support. I am using reverse-engineer code-first against an existing SQL server database to generate my base code. The application works fine against a SQL Server database.
I am using System.Data.Common.DbProviderFactories.GetFactory to generate the provider.
System.Data.EntityClient.EntityConnectionStringBuilder connectString = new System.Data.EntityClient.EntityConnectionStringBuilder(a_Connection);
System.Data.Common.DbConnection conn = System.Data.Common.DbProviderFactories.GetFactory(connectString.Provider).CreateConnection();
conn.ConnectionString = connectString.ProviderConnectionString;
LB500Database = new LB402_TestContext(conn, true);
a_Connection is provider=IBM.Data.DB2;provider connection string="Database=LISTBILL;User ID=xxxx;Password=yyyy;Server=db210:50000"
and is being parsed correctly by the EntityConnectionStringBuilder.
I then try to access a table in the database with
LBData500.LB_System oneSystem;
System.Linq.IQueryable<LB_System> allSystem = LB500Database.LB_System.Where(g => g.DatabaseVersion == databaseVersion && g.CompanyID == companyID);
I get an invalid operation exception "Sequence contains no matching element" which means that no elements are returned. If I remove the Where so that all rows are returned (there is one in the table) and try to enumerate the result set using the VS debugger I see the message:
"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe."
I am not using multi-threading. I am not inside the OnModelCreating.
Just changing the connect string to point to SQL server works fine, so I think my basic approach is sound. If I were getting some kind of error back from the server I would have something to go on. I can run the query from inside Visual Studio, so I have connectivity.
Any pointers would be appreciated.
UPDATE:
I turns out the EF objects were generated using EF5 and the EF6 runtime was being used. I regenerated the EF objects using EF6 reverse engineer code first. I can now connect to the database and get an error message:
"ERROR [42704] [IBM][DB2/NT64] SQL0204N \"DBO.LB_SYSTEM\" is an undefined name."
The schema in the DB2 database is the same as my userid (in this case, not always). I added the CurrentSchema=xxxx to the provide connection string, but EF is still passing dbo as the schema name.
Now I need a way to change the schema name at run time. I saw a link to codeplex EFModelAdapter (http://efmodeladapter.codeplex.com). So I may give that a try.
Update2 After looking through EFModelAdapter, I decided to take a different route. Since I only need database access and not schema management, I decided to go with Dapper (https://github.com/StackExchange/dapper-dot-net). This works great for what I need and allows me to change the schema name when accessing DB2 databases.
As per my Update 2, Entity Framework was a little overkill for what I needed. I switched to dapper https://github.com/StackExchange/dapper-dot-net and I am working fine against multiple DBMSs.

How to avoid data loss with EF Model First database schema upgrade?

This is a long question, but I would be very very thankful if I can get some good advice on this. In short, I’m looking for a good approach for version upgrade of MS SQL database schema that also demands data being moved from deleted tables into new tables.
I think Stack Overflow is the most appropriate place for this question (not dba.stackexchange.com) because at its core, this is an issue for .NET developers using Entity Framework, and the database parts of this consists mostly of auto-generated sql scripts.
Background
A .NET application and SQL database is running in Azure (The application in worker roles and the database in Azure SQL). Until now, version upgrades have worked fine, because all database schema changes have been simple (like adding a new column). However, from now on I also need to deal with moving data from one table to another during upgrades. (I’m able to fix this temporarily by creating a new database, generate a script with data from the old database and manually edit the script to make it fit the new schema, but I hope there is a better approach).
I use Entity Framework and I use Model First. Entities and associations are defined in Visual Studio Data Model Designer, and this approach is very appropriate for my application.
I use a dacpac to upgrade the Azure SQL database, and this approach has worked well until now (but now I will get data loss, so now I must find a way to move data to new tables).
I hope I can continue to use entity framework and defining entities/associations in the designer, but it’s fine to switch away from dacpac upgrade to another technology if needed.
Upgrade approach until now
I add new entities (tables), associations (relations) and properties (columns) in the designer.
I right-click, pick “Generate Database from Model…” and this results in a .sql script that drops old database objects and creates the new database objects.
I create an empty database and run the script to create the tables/keys etc.
In SQL Server Management Studio, I right-click the database and pick “Tasks -> Extract Data-tier Application…”. When the wizard completes I get the dacpac I need (Actually I can now delete the database, since I only created it to be able to get the dacpac file, since I don’t think I can generate it in Visual Studio Data Model Designer).
I right-click the Azure SQL database and pick “Tasks -> Upgrade Data-tier Application…” and follow the wizard.
Until now I have never had data loss, so this has worked fine!
Current situation
This is a simplified example to illustrate the issue, but I will get into almost identical situations quite often from now on it seems. Look at the old and the new version of the schema in the figure below. Assume there is already data in the database. I need the data in ImageFile to end up in ImageFileOriginal or ImageFileProcessed depending on the IsOriginal boolean/bit value. Using “Upgrade Data-tier Application” I will get alerted of data loss. What approach would you recommend to deal with this? As I said earlier, it’s fine to switch away from dacpac upgrade to another technology if needed.
I have read about Visual Studio Database Projects, Fluent Migrator, Red Gate and Entity Designer Database Generation Power Pack (It doesn't support Visual Studio 2012), but I didn’t find a good way for this. I admit I haven’t spent a whole day digging into each technology, but I certainly spent some time to try finding a good approach.
The best way to migrate database schema (create / delete tables / columns) and also data, is using the SSDT - Sql Server Data Tools, available for Visual Studio 2010 and Visual Studio 2012.
Here are some very useful links:
http://msdn.microsoft.com/data/tools
http://blogs.msdn.com/b/ssdt
http://msdn.microsoft.com/en-us/data/hh297027
In the Configuration class set the constructor as below:
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = false;
}
Set the AutomaticMigrationEnabled property to true
means we are using automatic code first migration and another property AutomaticMigrationDataLossAllowed is set to false, means that during the migration no existing data is lost from that migration of the table of the database.
The entire Configuration class is as follows.

Entity Framework: what do I do with edmgen.exe's output?

I'm forced to use a legacy SQL Server 2000 database for an EF-based app I am writing. The tables already exist, so I need to generate the Entities layer. I can do this in VS2010 using MySQL and recent versions of SQL Server, but not 2000.
To get around this, I followed some tutorials that explain how to generate csl, msdl and ssdl files using edmgen.exe.
That works fine. I now have those files in e.g. c:\temp.
Please can someone tell me what to do with these files? I want to Entity Framework-ify a simple console application that I have written. Can I somehow create an 'ADO.NET Entity Data Model' from these files so I end up with what I would have if I had used VS2010 all along?
Thanks
I got it working, here is what I did
1) Use edmgen.exe to generate the files mentioned in my question
"C:\windows\Microsoft.NET\Framework\v4.0.30319\edmgen.exe" /mode:fullgeneration /c:"Data Source=<your_server_here>; Initial Catalog=<your_catalog_here>; UID=<username>;PWD=<password>" /project:<vs2010_project_name> /entitycontainer:<project_name>Entities /namespace:<project_name>Model /language:CSharpEntityFramework
2) Follow these instructions "How To: use your existing CSDL/MSL/SSDL files in the Entity Designer CTP2" - its actually for VS2008 but it worked for me too.
http://blogs.msdn.com/b/dsimmons/archive/2007/12/07/how-to-use-your-existing-csdl-msl-ssdl-files-in-the-entity-designer-ctp2.aspx
3) I had a further problem in that my legacy db had no primary keys so I followed these instructions which also worked
http://pratapreddypilaka.blogspot.in/2012/04/entity-framework-adding-datatable-with.html
These files are referenced in EF's connection string and EF use them at runtime to build a mapping but it can still not work because SQL Server 2000 is not supported by EF (at least EF 4.0 and newer). EF can generate SQL not supported by SQL Server 2000 and you will get exceptions at runtime.

How to view generated SQL from Entity Framework?

As the title says, how do I view the SQL generated by Entity Framework from within my code? I'm running into an error where the EF is crashing because a field is generated by the database (a DateTime field), and I thought I set it to know that the store is generating it via StoreGeneratedPattern, but it's still crashing, so I would like to see what exactly it's trying to push up to the database.
P.S. I've only been using EF for about an hour now... Switching from L2S.
Since you don't have Sql Profiler, your best choice would be LINQPad. You can use your existing assembly.
Click Add connection -> Use a typed data context from your own assembly -> Entity framework and select your dll.
You can write queries directly against your model (or copy-paste from your code). Select the SQL 'tab' under the query window to view the generated SQL code.
You can use the Entity Framework Profiler (EFProf). It's not free, but there's a 30-day trial available. It does a lot more neat stuff besides showing you the SQL statements.
Generally, you should always use SQL Profiler to see the SQL statements that being submitted by EF into your database.
Also, I think you misunderstood about what StoreGeneratedPattern is. If you look at its possible values inside the model, you'll see that it has identity meaning that the value will be generated (by the database) when the row is inserted and will not otherwise change. The other options are Computed, which specifies that the value will be generated on inserts and updates, and None, which is the default.
So EF will not generate that DateTime field on the fly for you, you need to manually create it and then update your model from database so that EF will generate appropriate metadata to work with it at runtime.
The free AnjLab Sql Profiler will work if real SQL Profiler is not available because you're using SQL Server Express: http://anjlab.com/en/projects/opensource/sqlprofiler. It's not quite as nice as the real thing but it gets the job done well enough.
One solution would be to capture the network traffic and have a look at the data on that level. Microsoft Network Monitor does a good job of this.
Of course, that only works if you're using a separate DB server, and the connection is not encrypted.