Entity Framework and stored procedures with custom entities - entity-framework

I've got an existing EF4.1 project which is working just fine. I've added a new SP to the DB which returns a new kind of an entity (an existing entity with some additional fields).
The problem is when I try to import the function to the EF - it won't create my complex type. the wizard writes that "no database connection has been configured for this model". Which is strange - because it does see the new SP and everything.
I've tried creating my own, new complex type, but it won't map the fields as needed (some type conversion issues)
Any ideas what could be done?
Thanks!

To build on Malako's answer, I have a simlar situation. My problem was that my connection strings are in an external file
<connectionStrings configSource="some_other_file.config">
The "Update Models" wizard has a bug where it will not look in the external file for connection strings, and I cannot leave a connection string in the connectionStrings tag since it must be empty or it will give an error when building.
The workaround for me is to use the Update Wizard, check the box that says "Save entity connection string in Web.config", and then add all my function imports. When I'm done, I comment out the connectionString so my project will build. Next time, uncomment that entity connection string before updating models.
Annoying, but at least there's a way to get it to work.

For me, how I got it to work in my model project. There was other connection strings I left in there that had "server=" in there (non-EDMX related). I just deleted those other connection strings and the EDMX update wizard works as advertised.
Error message seen: Unable to update the App.Config file because of the following exception: 'The 'server' keyword is not supported.'

I assume the ConnectionString property of the entity model is empty. Check in model browser.
The easiest way to fix this is to remove all the connection strings in the .config files. Do a search for
connectionstring="
Delete the line(s) entirely or comment it/them with
Delete your edmx and recreate it. Make sure 'Save entity connection settings in Web.config as:' is checked.
Now the ConnectionString should be set and you will be able to generate complex models via function import.

if it still not works for you then remove other connection strings. and re add new.
the same problem is solved by this. removing all the connections string and added the Entity framework's connection string first then added the others but changed the name.

My solution to this same problem (VS2013) was this:
Go to Model Browser
Right click YourModel.edmx
Update Model from Database
Then it prompted me to select the connection. I selected the connection I wanted and proceeded to the next screen.
Add/Refresh/Delete what you need.
Select Finish and voila, the connection is here.

You have to add the connection string again every-time you add a stored procedure. Otherwise it will be no map when you try to get the columns you get a message on the "Edit Function import" you will See a message saying "No database connection has been configured for this model".
So my workaround is to re install the stored procedure again but what happens when I have 20 or more then every time I will have to re do all stored procedures. Or create a new model, this is the cons of this.
Here is the link of my solution there is a video and everything but I'm trying to figure How to do it with out deleting the model or adding the connection string VIDEO LINK OR stack overflow solution since there is not way yet to map store procedure I use a class my company has to retrieve has table from the store procedure and then send the data as JSON String if you want that solution let me know and then I will tray to do the code with the explanation (its done with a .dsn conection string and ODBC "Open Database Connectivity").

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"

using EF migrations with SQL Server (Not express/localdb)

New to EF.
Am using code first but created from an initial database.
First issue is when I added a foreign key to the model After executing add-migrations from the console it created migrations to create the entire tables rather than just adding the foreign keys to the existing tables using AddForeignKey(....),
And when I try to update-database it tries to create a localdb database under and i get the error
Directory lookup for the file "C:\src\Project\App_Data\TheDatabase.mdf" failed with the operating system error 2(The system cannot find the file specified.).
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Which kind of makes sense because i'm not using sqlexpress.
It seems as though I need some configuration to coax it into action.
Any useful advice would be welcome.
I found a solution although maybe this is more of a workaround
I did change the connection factory but it did nothing. Still tries to use App_Data folder and looks for an MDF there.
I found a work around though. The package manager lets you override the connection string so i just did that and it works fine.
As for the other part of my question regarding why it was trying to create the tables. What I needed to do first it use the Add-Migration with -IgnoreChanges and update-database will then store an initial blank migration so from then on, any changes you make will be just those incremental ones I was referring to.
Here was the link for that. https://msdn.microsoft.com/en-us/data/dn579398.aspx?f=255&MSPPError=-2147217396
Thanks to those who offered help.
Hope this helps. Basically, EF needs your first snapshot of your database to create the model classes as the initial state, after that you can add migrations.
If it doesn't help, can you post your connection string and number of migrations your have?

Insert data using LinqPad and Entity Framework

Is there a way to insert data using LinqPad and the entity framework?
You need a "Context" of some kind to do an Add or AddObject. I can't find how to get that reference.
I tried making one but then I go this error:
ArgumentException: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Any one know a cool way to insert/update in LinqPad with Entity Framework?
In order to use Entity Framework from LINQPad, you would need an existing data context since LINQPad can only generate LINQ-to-SQL data contexts (if you don't already have a project with such a data context, create one and build it)
Click "Add Connection" on the left side of LINQPad.
Select "Use a typed data context from your own assembly".
Select "Entity Framework" from the list.
Click "Next >".
In "Path to Custom Assembly" enter the path to the DLL/EXE file containing the EF data context.
In "Full Name of Typed ObjectContext", click "Choose" to find the EF data context, and the same for "Path to Entity Data Model".
Configure the database connection settings.
Click "Test" to verify everything works.
Click OK - you're ready to go.
What I was missing was the connection string.
I had to copy the connection string from my App.config file (replacing the " with ') and put it in the constructor of my ObjectContext.
After I did that it all worked fine.
if you are using a C# program type, this.Connection.ConnectionString will give you the connectionstring which you can then pass into the ctor of context.

Does the Entity Framework use a default intital catalog and what assumptions does it make?

I did (pretty much) everything correct in a new EF project, but I forgot to use the named connection string in the EF context class, so, it used the default.
It created a new database inside the SQL Express default data directory, and it worked perfectly.
When I realised my mistake (After wondering for ages why no files were showing up in the app_data folder), I renamed the class to use the named connection string and then I kept getting the following error:
Unable to complete operation. The
supplied SqlConnection does not
specify an initial catalog.
I know how to fix this, but, EF is like magic to me! I can't believe it works as well as it does and I am just curious as to what it uses by default / is there a list anywhere of "assumptions" that EF uses on your behalf if you specify nothing?
By default it uses database with the same name as your context but once you specify custom named connection string you must provide the name of used database either by Initial Catalog or Database parameter.
I had the same problem but I figured it out by changing the web.conf. You need to specify an initial catalog and Integrated security and make a user instance.
Here is working web.conf:
add name="MovieDBContext"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|Movies.mdf;Initial Catalog=Movies;Integrated Security=SSPI;User Instance=true"
providerName="System.Data.SqlClient"

Number of members in conceptual type does not match with number of members on object side type

I'm using .net framework 3.5 SP1.
After adding a column to one table in Sql Server (as well as changing an existing column from allowing nulls to not nullable), I can no longer run my project without getting this error:
The number of members in the
conceptual type
'XBRLDimensionalModel.axis_t' does not
match with the number of members on
the object side type
'EOL.Xbrl.Persistence.Data.axis_t'.
Make sure the number of members are
the same.
I gave up trying to find and fix the generated code. I now have deleted all my local entity-related files and re-generated them by starting over from scratch and adding a new item (ADO.NET Entity Data Model). I still get this error.
The only way I can run the project now is to undo all my pending changes and use the last version from source control, and of course change the two modified database columns to nullable.
From all I've read so far it seems like I simply should have been able to "update" my model from the database. That resulted in this exception (above). But now I'm totally confused that even with a complete regeneration of the entity model and supporting classes I'm still getting that error.
I changed the property on my edmx model: "Metadata Artifact Processing" to "Copy to Output Directory". The Designer.cs, csdl, msl, ssdl files all seem to be consistent with the latest DB changes.
The exception is being thrown the first time my entityModel instance is referenced. So it is prior to any loading or saving of the data from the changed table.
any ideas where I'm going wrong?
Thanks,
TG
This error can also happen if the EDMX file was changed outside Visual Studio. Right click on the EDMX file and click "Run Custom Tool"
Open your model as XML. Remove all references to that type from the CSDL. Save and close, then reopen in the GUI. Now you should be able to update model as usual. If that doesn't work, do the same thing, but remove from MSL as well.
This seems a little verbose for a comment so I'm adding this as another answer:
In response Craig's suggestion I opened the edmx file in an XML viewer and removed all references to Axis_t (including the associations due to Foreign Keys). From the entire file.
I then "updated" the model by opening the edmx file as the GUI interface, right-click | refresh from database | Add (tab) which now only lists the Axis_t table. I added the table which seemed to work fine and included my new column and the column was mapped correctly.
I then ran the project to the same result. Same error as posted above.
I have now reverted back to what was in source control as well as changing the database columns (new one and modified one) as nullable. The project runs fine. I still have not successfully been able to implement the new DB column in EF. It behaves as if there is some stored/compiled version of the model which is not being updated via the "update" process.
When changing a foreign key from nullable to non-nullable (or vice-versa), be sure to change the association multiplicity from 0..1 to 1 (or vice-versa). The designer sometimes misses this in an update from the database.
Right click on your edmx file and open with XML.
Find the incorrect data types and change them.
Save file.
This worked for me.
I was facing the same issue, when I added one column to db and added respective property to entity(edmx).
I was also using source control for my solution. As I noticed, while saving changes to any file, save action prompts with overwrite option.
So, I overwritten the designer.cs as well config file and problem gets resolved.
regards,
bhushan
This has happened to me when I am working on two versions of the same application (with Model differences) that compile into the same folders.
It appears that Visual Studio doesn't "clean out" the "obj" temp folder properly and some fragments of the old model are still in there.
If I simply delete all files from the "obj" folder and re-compile this error goes away.
The Model in each version is perfect which was driving me crazy.
Not saying this is the answer to the OP's question but it is definately another reason for this error.
Steve
I had this same issue for hours. Found that in my Designer.cs file one of the properties of my entity was missing its attributes. (Don't know how this happened?)
[EdmScalarPropertyAttribute(EntityKeyProperty = false, IsNullable = false)]
[DataMemberAttribute()]
public global::System.Int32 ContractCapacity
Now the error message makes sense, this was the missing DataMember. Once the attribute was added IT WORKED!!!
Here's a nightmare scenario that I just experienced: I have an MVC2 website and a WCF service that are built separately, but share a configuration. Within both projects, I used the same Entity Container Name; therefore I picked up the same connection string for both projects. Eventually the metadata got out of sync between the two and caused this error. The obvious solution was to not use the same Entity Container Name in the two projects; changing to a different name allowed me to specify unique connection strings, and therefore metadata, for each component which avoided the problem.
Now that I figured it out, it's obvious, but I had a tense hour or two!