Connecting to an existing database in a ASP.NET MVC4 Web API project - asp.net-mvc-4

I'm building an web api using ASP.NET web api framework. I have seen a few tutorials on how to get started but I haven't found to use an existing SQL Server database. I have the database up and running also added the data connection to the database explorer in VS but I don't know how to connect the database to my project so I can start using it as my repository. How can I do that?

Put the following in your application web.config file and replace "yourConnectionString" with the actual connection string.
<configuration>
<connectionStrings>
<add name="DbConnection" connectionString="yourConnectionString" />
</connectionStrings>
</configuration>
In the code use System.Configuration.ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString to get its value. You might need to reference the "System.Configuration" assembly in your project.

Related

Could not resolve host '(localdb)' on Visual Studio for MacOS

Developing an Asp.Net web Api working with SQL. I'm stuck at debugging app on my Mac. When calling methods, working with db, app returns instead this error:
System.Net.Sockets.SocketException
Could not resolve host '(localdb)'
Feels like a mistake is somewhere in this line (according to other answers): Web.config file
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(localdb)\MSSQLLocalDB; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|MyDatabaseContext-12.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
This app works perfectly fine in VS for Windows. Any ideas?
Update: I have an sql server in azure, so I have a connection string. Any way to make it used instead of local?

ELMAH for ASP .NET MVC Windows Application

I need to log errors for an asp.net mvc windows application which also uses entity framework and for doing this i thought of using ELMAH.
My App.config file contains the appsettings for providing folderpath and other file related details.
Now when I try to add the configuration (elmah...../elmah) for ELMAH after installing it in my project it throws an exception "Configuration system failed to initialize".
But when I remove that code then it works fine.
Please provide me the solution to log errors for MVC windows application.
And the final question is ELMAH.mvc free to use or not?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="folderpath" value="~PA\FileImport"/
<add key="XMLFolderPath" value="~\FileImport\XML"/>
</appSettings>
<connectionStrings>
<add name="####" connectionString="############"
providerName="System.Data.EntityClient" />
</connectionStrings>
<elmah>
..........
</elmah>
</configuration>
It sounds like there's a problem with your ELMAH configuration, since ELMAH and EntityFramework normally doesn't interfere with each other. I would recommend you to follow a tutorial like this: ELMAH Tutorial. There's a ton of tutorials for ELMAH outthere, why a simple google search will find a lot of resources.
If following a tutorial doesn't work, you should probably add some additional information and web.config code in this thread, since figuring out your problem from the amount of information, is almost impossible.

MVC4 - Membership - SQL Server Compact 4.0 - Exception: Unable to find the requested .Net Framework Data Provider

The InitializeDatabaseConnection Method documentation says we can use the MVC 4 "Internet" template's generated membership functionality with SQLCE (SQL Server Compact 4.0 Local Database).
I've used this template many times before and have never had a problem when I didn't fiddle with anything and simply used the localDb (the default) that is generated by the Entity Framework the first time we register a user.
My requirement is to get the membership tables that are by default generated into 2012 localDb database instead to generate into a SQLCE database. However, I'm getting the following:
Exception: Unable to find the requested .Net Framework Data Provider. It may not be installed.
To do this we simply:
Open Visual Studio (express works fine).
Generate a new MVC4 --> Internet (with account) project.
Add a SQLCE database to the ~/App_Data/ folder (right-click the folder and select Add --> SQL Server Compact 4.0 Local Database).
Add table then a record to the table.
Right-click the Models folder and select Add --> ADO.NET Entity Data Model
Open the (root) web.config and copy the name of the 'connectionstring'(<add name="ceEntities")
Locate the following line of code in the ~/Filters/InitializeSimpleMembershipAttribute class: WebSecurity.InitializeDatabaseConnection("ceEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
F5 to compile/run/debug the project
Once the home/index page loads click the "Register" link in the upper right hand corner
Enter a username and password to register and click 'Ok.'
Up to this point the code compiles and runs fine however when the following line of code is run in the ~/Filters/InitializeSimpleMembershipAttribute class:
WebSecurity.InitializeDatabaseConnection("ceEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
This exception is caught:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Which is apparently fixed when we add this code to the web.config:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<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>
And when we run it again the following exception is caught:
Unable to find the requested .Net Framework Data Provider. It may not be installed.
Thank you to Scott Hanselman and whoever made him aware of the Membership Provider with SQLCE protocol as in his Introducing System.Web.Providers - ASP.NET Universal Providers for Session, Membership, Roles and User Profile on SQL Compact and SQL Azure blog post Scott outlines the steps to implement the ASP.NET Universal Providers. This helped me as he outlined the proper connection string outline for SQLCE:
<connectionstrings>
<add name="Sql_CE"
connectionstring="Data Source=|DataDirectory|\MyWebSite.sdf;"
providername="System.Data.SqlServerCe.4.0">
</add>
</connectionstrings>
So I updated my connectionstring to:
<connectionstrings>
<add name="defaultconnection"
connectionstring="Data Source=|DataDirectory|\ce.sdf;"
providername="System.Data.SqlServerCe.4.0">
</add>
</connectionstrings>
Then updated connectionStringName the ~/Filters/InitializeSimpleMembershipAttribute class back to:
WebSecurity.InitializeDatabaseConnection("defaultconnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
The application compiled without an error or exception so I ran the application then Registered a user and in that process the applicable SimpleMembership tables were generated into my "ce.sdf" (SQL Server Compact 4.0 Local Database).
I am now able to utilize the SimpleMembership default's at their fullest!
p.s., For brevity I'm going to now edit my initial post/question to omit the stacktraces, leaving only the exceptions.
Random suggestion but it may need to be added.as a namespace to the web.config file or as a package in the packages file, I could be wrong

Issue with unwanted connection string appearing in my published web config

I’ve been testing the new web deploy tool with VS 2012 but I have this issue:
I get this extra connection string added to my published web config that I don't currently have in my projects web config.
<add name="name" connectionString="name_ConnectionString" providerName="System.Data.SqlClient" />
Where could this be coming from? It seems like is a relic from past conn strings I've used..
Hope this explains my issue :0)
Thanks for any assistance
Quantum
It has to be coming from one of the web.config files.
Have you checked if a transform to your web.config is applied or not. Check web.release.config, web.debug.config file to check if the connection string is still there.

Sharing Entity framework objects across projects?

I am having some refactor troubles, maybe someone knows why...
In one solution I have a WCF service. In another solution I have a RIA application. Since the SQL database between these two is identical, I wanted to create a separate project, in which to host the edmx file as well as a domain service. If I create the edmx file in the WCF project directly, and do the same on the RIA side, everything works fine.
But when I try to pull this edmx file into a separate project and add references to it I get all kinds of bizarre errors that my entity objects cannot be found. The WCF service itself seems fine, in that it references the edmx project and compiles just fine.
But the WCF client project, that has a service reference to the WCF service pukes on the entity references. Even adding the edmx assembly doesnt really help- some entities are found others are not. Very odd.
Anyone know what Im missing?
Copy the connection string across all your projects which attempt to use the model.
However, in the connection string, remove the OR'd Resource pointers.
e.g. Full Entity Connection
<connectionStrings>
<add name="AwesomeEntityModel"
connectionString="metadata=res://*/AwesomeEntityModel.csdl|res://*/AwesomeEntityModel.ssdl|res://*/AwesomeEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=NEILHIGHLEY.COM;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Trim it to the following;
<connectionStrings>
<add name="AwesomeEntityModel"
connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=NEILHIGHLEY.COM;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Based on what you've posted so far and taking it that you've ensured that the "edmx" project has a new namespace that is also used by the other projects.
If I'm reading what you've said correctly:
your WCF server references the "edmx"
project.
your WCF client references the WCF
server AND the "edmx" project.
It could be something as simple as circular referencing conflicts. Make sure that any "edmx" reference data within both of the other projects aren't public, just in case the client is picking up "edmx" data from the server project.
Also check whether missing items are left at the default accessibility of internal (when not defined).