External SQL Server access in MVC 3 + Entity Framework for query-only - sql-server

I'm devoloping a system using MVC 3 with EF 4. In this system, I need to lookup some information that already exists in an external database.
Saving me project's information on my database is OK. I defined my Models on it and let DbContext create the tables on my server.
The problem is when I try to query some data from the external database. I've added the connection string in the properly place on Web.config:
<connectionStrings>
<add name="ExtDBConnectionString" connectionString="Data Source=path.to.server;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=pass;Pooling=True;Min Pool Size=5;Max Pool Size=60;Connect Timeout=2;" providerName="System.Data.SqlClient" />
</connectionStrings>
Is it possible to just create some queries to this server on my project without the overload of recreating all the Models from this external database? I know I can recover this connection string on my code by using the command System.Configuration.ConfigurationManager.ConnectionStrings["ExtDBConnectionString"].ConnectionString, but how can I create a connection and instantiate my queries?
Thanks in advance!
Edit: #rouen called my atention I didn't explicitly said the databases are differents. They do not share the same schema! The external database is the output of a report; so, I need to traverse it on my project to import the relevant lines to the local database.

I would just use standard ADO.NET. Use the SqlConnection and SqlCommand classes.
ADO.NET Examples on MSDN:
http://msdn.microsoft.com/en-us/library/dw70f090.aspx

Is the remote database schemantically identical as your local ? If yes, you can pass connectionstring to constructor of ObjectContext/DbContext, and it will use that database.
http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx

Related

Azure: The context is being used in Code First mode with code that was generated from an EDMX

I have MVC app running fine in local. After updating to Azure, it started throwing the error:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project.
I have checked if there is any difference between the local web.config and azure web.config. except the credentials, everything is same. And it read:
<add name="DBEntities"
connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=xx;initial catalog=xx;persist security info=True;user id=xx;password=xx;MultipleActiveResultSets=True;application name=EntityFramework""
providerName="System.Data.EntityClient" />
I am using EF 6.1.3, MVC5
I ran into the same error message and managed to solve it with the help of this post here on StackOverflow.
In the Azure Management / Web Apps / [Your web app] / CONFIGURE / connection strings , make sure of 3 things :
The connection string has the same name as the connection string in your project.
The connection string Value contains all of the metadata as appears in the connection string in your project. Mine looks like this:
metadata=res://\*/Models.[MyModel].csdl|res://\*/Models.[MyModel].ssdl|res://\*/Models.[MyModel].msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:[myDBServer].database.windows.net,1433;Database=[myDB];User ID=[myDBUser]#[myDBServer];Password=[myPassword];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
The third column (default set to SQL Database) is set to Custom
Found a simpler solution than adding all the stuff in the Azure connection string. I just changed the connection string name in Azure. It worked..
I had to deal with the same issue. The solution was
Connect to the website by FTP
Edit web.config
Add following connection string:
add name="NewDatabaseEntities" connectionString="metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:your.database.windows.net,1433;initial catalog=your;integrated security=False;User Id=your;Password=your;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
Thanks Microsoft for poorly documentation of EntityFramework Database First on Azure.
You need to change this line metadata=res:///NewDatabase.csdl|res:///NewDatabase.ssdl|res://*/NewDatabase.msl;
to
metadata=res://*/;

How to keep membership and my data in the same database?

I'd like to store all my membership and my data in the same database. I've started by creating a database called MembershipDB where I added membership schema using aspnet_regsql.exe.
I'm using Internet ASP.NET MVC4 template. So this is the connection string
<connectionStrings>
<remove name="DefaultConnection"/>
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MembershipDB.mdf;
Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
When I create a user, I don't see any data in the MembershipDB database I created previously. Instead, I see another database called MembershipDB.mdf that was created and that contains the data.
Why my database is not getting the data, instead another database with the same name is being created?? Code first is supposed to create a new database only if it doesn't find one with the same name.
Thanks for helping.
Your connection string specifies an initial catalog(database) of MembershipDBA.mdf. Change it to MembershipDB. The .mdf part is just a standard file extension for the data part of the database. There is no need to reference it unless you are specifically changing something to do with the files.
Just use the database name as in the connection string without the .mdf extention.
Set connectionStringName="MembershipDB" in the Membership section of web.config
I think the best approach (I use it all the time) is to look and watch what others do in these cases and repeat after them.
Here is an article (although EF 4.1, not 5) on how to use EF and membership together (and this is what you're after if I understood your question correctly:
Using Entity Framework Code First and ASP.NET Membership Together
Here is successfully answered question on SO (same topic) (wonder how didn't you found this one prior to asking yours):
Best database design approach to join complex data to ASP.Net Membership tables
Please let me know if this is of help.

asp mvc 3 noobie: CREATE DATABASE permission denied in database 'master'

I'm an asp mvc 3 noobie. I've done a few tutorials and am now ready to keep learning by trying to build a site.
In all the tutorials, you connect to a SQL CE or SQL Express DB. But I want my site to build a DB on sql server.
I created a database on my networked server that I'll call MyDB. Then I set my connection string in my web config file like this:
add name="ApplicationServices"
connectionString="Data Source=Server\ServerInstance;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient"
I created models and a scaffolding controller.
I created a simple DataBaseContext like this:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
But when I hit the following line in the scaffolding controller, i get the error:
Function Index() As ViewResult
Return View(db.Employee.ToList()) //CREATE DATABASE permission denied in database 'master'`.
End Function
Should I fix this by changing the permissions on the MyDB database? Is this a permissions issue on the SQL server side? I am confused why I am getting a Create database error because the DB already exists.
Am I getting this error b/c I have already created the database? Does the scaffolding want to create the database somehow?
Sounds like it is trying to create a new DB by the error message. I'm guessing that you are using EF code first with your project and using it's migration capability to build your DB. Check the setup of the EF context to make sure it's using your connection string.
The connection string or its name can be passed to constructor of DbContext. If you are using default constructor it searches for the connection string with the same name as the name of your derived context class. Basically, make sure your connection string has the same name as your derived dbcontext class and it should find it.
See this post for additional information
1.You need to set IIS app pool identity to be ASP.NET integration mode.
2.Add a login in SQL Server for IIS APPPOOL\ASP.NET.
3.In SQL Server, set IIS APP POOL login to have dbcreator role.
USE master;
EXECUTE sp_addsrvrolemember #loginame = N'YourAppUserLogin', #rolename = N'dbcreator';
<add name="Default" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=test2;user id=sa;password=123456"
providerName="System.Data.SqlClient" />
Use this connection string for your application

ASP.NET membership using SQL Server

I am trying to create an MVC 3 app using asp.net membership in a sql server database. I want to be able to use the Entity Framework for development on this app.
I have created by database and used the aspnet_regsql utility to add the membership tables to the database. The part I'm stuck on is how to connect to this database using my application.
I have added an entity model to the project which generated a new connection string in the web.config and I have tried changing the connectionStringName property on all the membership related entries to the new string like so:
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="BlogV1Entities" applicationName="/" />
but this is not working as I am getting errors when trying to create a user through the app or ASP.NET Configuration utility
An error occurred while attempting to initialize a System.Data.SqlClient.SqlConnection object. The value that was provided for the connection string may be wrong, or it may contain an invalid syntax. Parameter name: connectionString
Can anyone point me in the right direction to properly get this setup so my app can access the database?
EDIT: In response to first comment this is what the connection string looks like this:
connectionString="metadata=res://*/BlogV1Model.csdl|res://*/BlogV1Model.ssdl|res://*/BlogV1Model.msl;provider=System.Data.SqlClient;provider connection string="data source=jesse-laptop;initial catalog=BlogV1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
the entity framework connection string won't work when using asp.net membership. I have dont in my project like this;
i-e You need separate connection string for that;
your membership connection string;
<add name="DAConnection" connectionString="Data Source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True" providerName="Syste.Data.SqlClient" />
you entity framework connection string;
<add name="DAEntities" connectionString="metadata=res://*/Models.DAModel.csdl|res://*/Models.DAModel.ssdl|res://*/Models.DAModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=E:\MYWORK\DIGITALASSETSMVC3\DAMVC3\APP_DATA\DAMVC3.MDF;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
It's not a valid connection string which can be used by Membership, it's kind of special connection string just can be used by EF (because of different provideName which Membership expect AFAIK).
Add a clear regular connection string and reference to it instead.

Microsoft Enterprise Library - How to create database based on Type

I'm using Enterprise Library 4.1.
I have a new feature to implement and it requires the use of mysql.
I have found Enterprise Library Contrib, which adds functionalities to use MySQL with Enterprise Lib.
Works great.
To get it to work, you need to call the method 'DatabaseFactory.CreateDatabase(connectionStringName);' like you would normally do. The connection string name is stored in the configuration and linked to the database provider mapping configuration section.
As an exemple:
<dataConfiguration defaultDatabase="MyDefaultDb">
<providerMappings>
<add databaseType="EntLibContrib.Data.MySql.MySqlDatabase, EntLibContrib.Data.MySql, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null"
name="MySql.Data.MySqlClient" />
</providerMappings>
</dataConfiguration>
<connectionStrings>
<add name="MyDefaultDb"
connectionString=""
ProviderName="System.Data.SqlClient" />
<add name="acb_leaderboards"
providerName="MySql.Data.MySqlClient"
connectionString="" />
</connectionStrings>
Unfortunately, my application will connect to multiple MySQL database and the conncetion will vary from time to time. I can't have the mysql connection string be specified in the configuration.
I want to create a MySQL database object based on the providerMapping configuration.
How can I do that?
Thank you.
PS.
English is not my first language, I'm trying my best.
If you know ahead of time that you're using MySql, and assuming that the MySqlDatabase class follows the same patterns as the Database classes in the core Entlib, then you can just new it up directly, you don't have to go through the factory method.
Database mySql = new MySqlDatabase(currentConnectionString);
should just work. You only need to go through the factory if you're pulling named connection strings from config.

Resources