Azure web site deployment throwing. Mislead between DataBaseFirst and CodeFirst - c#

I'm stuck with this "dreadful" error message trying to deploy an MVC web site on Azure :
Code generated using the T4 templates for Database First and Model
First development may not work correctly if used in Code First mode.
To continue using Database First or Model First ensure that the Entity
Framework connection string is specified in the config file of
executing application. To use these classes, that were generated from
Database First or Model First, with Code First add any additional
configuration using attributes or the DbModelBuilder API and then
remove the code that throws this exception.
DataBase First Workflow was used from scratch (adding ADO.Net Entity Data Model element and following wizzard connecting to an Azure SQL Server DB). So I can't figure out why it's besetting me with Code First. Using EF 6.0 with T4 templates. Generated DbContext looks like this :
public partial class MyAppEntities : DbContext
{
public MyAppEntities()
: base("name=MyAppEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<AType> AType { get; set; }
public virtual DbSet<BType> BType { get; set; }
// etc.
}
Connection string looks like this. Copied both in DAL project and StartUp project web config :
<add name="MyAppEntities" connectionString="metadata=res://*/MyAppModel.csdl|res://*/MyAppModel.ssdl|res://*/MyAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ndkkyxvogj.database.windows.net;initial catalog=DbName;persist security info=True;user id=myuserid;password=Pa$$word;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
App runs without any problem on local machine.
Deploying process on Azure follow these steps.
Create (custom creation) web site on Azure and give db credentials
Download publish profile from Azure dash board
In VS click Publish from start up project and set following parameters :
-> Profile : Import downloaded profile
-> Connection : Connection well set and validates
-> Settings : Not sure at all what is awaited here !!! I tryed both connection settings : With suggested connection strings and with EDMX connection string. like this :
metadata=res:///MyAppModel.csdl|res:///MyAppModel.ssdl|res://*/MyAppModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ndkkyxvogj.database.windows.net;initial catalog=MyDb;persist security info=True;user id=databaseuser;password=Pa$$word;MultipleActiveResultSets=True;App=EntityFramework"
Tryed to comment OnModelCreating(). Didn't work.
Also tryed to comment throw on UnintentionalCodeFirstException(). Didn't work either.
Despite research on other SO Q & A, couldn't find any reliable solution. Any help would be greatly appreciated.

Ok got it ...
Actually, falling on that post and that one, it appears that it is Azure misleading between the connection string names both given the same in Azure Sql Server and the Azure Web Site.
It has nothing to do with a whatsoever bad EF implementation between code first/model first or db first ...
So I gave connection string name a new one in the web App config, Context Class constructor, and in the azure web sites connection string name parameters ... And it worked.
It was a real pain figuring this out ...

Related

WCF project trying to recreate database when it exists already

So I am attempting to utilize EF and my existing database in a WCF project in order to add some entities to the database.
Setup:
So I have several layers to my solution.
Core (class library)
Data (class library)
Services (class library)
WCFServices(WCF application)
WebUI (MVC project)
Entity framework 6.2.0 is installed in my Data, WCFServices, and WebUI project. (picture below).
So my database models are stored in the core project and my migrations for the database are stored in the data project. My web UI project has no issues accessing the database and using it. I have the exact same connection strings stored in both the MVC project and the WCF project.
MVC web.config connection string
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SQDCDashboard.WebUI-20190610100239.mdf;user id = exampleUser; password = ExamplePassword;Integrated Security=False" providerName="System.Data.SqlClient" />
The WCF project has the following connection string.
WCF web.config connection string
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SQDCDashboard.WebUI-20190610100239.mdf;user id = exampleUser; password = ExamplePassword;Integrated Security=False" providerName="System.Data.SqlClient" />
As you can see they both match exactly.
WCF service
public class OrderService : IOrderService
{
public string InsertOrder(OrderDTO order)
{
try
{
using (var context = new DataContext())
{
var productionLine = context.ProductionLines
.Where(x => x.ComputerName == order.ComputerName)
.FirstOrDefault();
if (productionLine == null)
throw new Exception("Production line could not be determined from computer name");
context.Orders.Add(new Core.Models.Order
{
MaterialNumber = order.MaterialNumber,
SerialNumber = order.SerialNumber,
ProductionNumber = order.ProductionNumber,
SalesNumber = order.SalesNumber,
OrderComplete = false,
ProductionLineId = productionLine.Id
});
context.SaveChanges();
return "Success";
}
}
catch (Exception ex)
{
return ex.Message;
}
}
}
The Error
So here is where the issue comes in. When I run the WCF test client to test my service, it throws the following error:
Cannot create file 'C:\Users\eric_obermuller\Source\Repos\SQDC Dashboard\SQDCDashboard\SQDCDashboard.WCFServices\App_Data\aspnet-SQDCDashboard.WebUI-20190610100239.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
This really confuses me because the database already exists. Why is it trying to create a new one? I am a bit of a beginner when it comes to structuring multiple projects in a single solution. So it could possibly be I just don't understand how EF is interacting between the projects?
I did notice that both my WCF project and my MVC project have their own database files in their respective App_Data folders. I have to say I am not sure how EF uses these files in conjunction with the actual local db, it has always sort of confused me so I may be missing something here (see below).
What I have tried
Originally I was using windows authentication but tried switching to SQL Server authentication (which is what I will end up using later).
I tried deleting the migrations folder in my project and dropped the database migrations table. I re-enabled migrations, added an empty migration, and updated the database.
I triple checked that the SQL Server account I am referencing has read/write permissions to the database.
Final Remarks
Again, I have 0 issues using the database within my actual MVC web UI project. My MVC project does use ninject to inject dependencies from my Service project into the controllers, it also injects the dbContext (stored in my data project) into some generic repositories (also stored in my data project), which are used in my Services class library project.
My WCF project does NOT use ninject in any manner, I am directly referencing the dbcontext, as this service is a very simple one and has no need for all that. So I could also see this being the possible issue?
Which DatabaseInitializer you have setup for DB migrations? if you are using 'DropCreateDatabaseAlways' initializer and have same database for two application running in parallel then that might be causing the problem.
While your MVC app is running fine, but WCF will fail while booting up the DBContext as it will try to drop and recreate the Database.
Change your database initializers to the one that would fit this scenario. "DropAndRecreateAlways/ModelChange" are not best candidates.

Entity Framework SqlException: Cannot open database "" requested by the login . The login failed for user ' domain\userid’

Entity Framework code-first deployment to company SQL Server issues.
I have an ASP.NET MVVM app that uses EF. It runs perfectly on my development laptop. However when I move the database to the company SQL Server, I'm having issues.
The connection string I’m using in my web.config is
<add name="ApplicationInventoryContext"
connectionString="Data Source=COMPANY_SQLSERVER; Initial Catalog=ApplicationInventory; Integrated Security=True;Connect Timeout=15;"
providerName="System.Data.SqlClient" />
The connection string should be OK as I’m able to connect and query the database using this connection from:
Visual Studio SQL Server Explorer
Microsoft SQL Server Management Studio
This is my DbContext:
public class ApplicationInventoryContext:DbContext
{
public DbSet<Application> Applications { get; set; }
public ApplicationInventoryContext() :
base("name=ApplicationInventoryContext")
{
Database.SetInitializer<ApplicationInventoryContext>(null);
}
}
This is the repository where I query the database:
public class DisconnectedRepository
{
public List<Application> GetApplicationsList()
{
using (var context = new ApplicationInventoryContext())
{
return context.Applications.AsNoTracking().ToList();
}
}
.....................
}
When I run the application I got the following error:
Entity Framework Exception SqlException: Cannot open database requested by the login
SqlException: Cannot open database requested by the login .
The login failed for user ' domain\userid’
How could this happens if the error shows the same login I'm using in the two connections above that are Ok?
Your connection string is specifying Integrated Security=True. That means it is trying to use the identity of the process running the application to access the database. Because it's a web application you're probably using IISExpress locally, which means it's running as the identity of the logged in user (i.e. you). Do you have permission to log into the company SQL server using the credentials you use to log into your computer? If not, there's your problem.
What seems unusual to me is that you're trying to hit the corporate SQL Server from your development machine. Most organizations don't allow developers to access production, so it's hard to tell if you're violating policy trying to do what you're doing or if that's just normal in your environment.
There are two options here:
Give your domain account a login on the corporate SQL Server. This isn't a particularly good option because if you're not the only developer then every developer is going to need to have the same thing done.
Create a SQL Server login and change your connection string to use UserId and Password rather than integrated security. That's still not a great option because now every developer will know the login credentials to the corporate SQL Server.
I will post the solution I found thanks to Steve . The response I found was here
stackoverflow.com/questions/4805094/
So what I did was just modify the constructor of the DBContext as under:
>
public class ApplicationInventoryContext:DbContext
{
public DbSet Applications { get; set; }
public ApplicationInventoryContext() :
base("Data Source=COMPANY_SQLSERVER; > Initial Catalog=ApplicationInventory;
Integrated Security=True;
Connect >Timeout=15;")
{
Database.SetInitializer<ApplicationInventoryContext>(null);
}
}
And it worked perfectly now .
Please look at the above link where you can find other approaches

Entity Framework creates a database with a wrong name

I have two projects in my solution:
An ASP.NET Web API project with EF
A console app with EF
Both projects are configured to connect to SQL Server and have the same connection string defined in the app/web.config:
<add name="AppContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=localhost\SQLEXPRESS;Database=XYZAC;Integrated Security=True" />
The problem only occurs with the console app. The web app creates the XYZAC database correctly. The console app, however, creates a database with the name along the lines of Namespace.AppContext, which isn't at all what I need. Because of that there is no communication between these projects.
I tried changing Database= to Initial Catalog= in the connection string of the console app, but it didn't change anything.
What can be the cause of this? Can this be happening because the API is logging in via IIS APPPOOL\XYZAC user and the app via WINSRV\Administrator? Seems unlikely, because both have pretty much the same permission groups and access to everything, but I'm not sure what else can be the cause.
What am I doing wrong here?
Edit: I'm sharing the DB models between these two projects. I'll try hard-coding the connection string into the constructor.
Try scaffolding from created xyz database to the console application and see if it connects with the scaffolded context .
Hard-coding the same string like this solved the problem:
public AppContext() : base("Sql n stuff;XYZAC")
Cool. As long as it works, right?

Entity framework can't connect to new table but only when deployed to Azure?

I am running Entity Framework 6.1.2 and I appear to have gotten myself into a bind. I am using the Code First approach.
I had a web site using a single database with two tables working just fine, both locally and when deployed on Azure. I then tried adding a new model and that's when things fell apart. I gave up on code first migrations because after a few hours of reading and trying the numerous steps necessary inside the Package Manage Console (3 steps per db context), the generated migration files always came out wrong. Usually empty, with no code at all in the Up()/Down() methods.
That's when I tried a manual approach. First I tried deleting and re-creating the database on Azure. At first I thought that worked, but for some odd reason only the two original tables were recreated by Entity Framework. The new table, and the child table it EF automatically due to a nested class in the new model, were not created.
Out of frustration I created the two new tables manually by copying the SQL query for the new table and child table from the SQL Designer window, and then executing those two queries against the Azure server. That worked and I did create the tables successfully on my Azure SQL server instance. However, my web site code can not connect with the new table(s). It can connect to the two "old" tables, but not the new one and its child table.
Remember, this code executes fine locally, but when run on Azure, any queries against the new table fail with the following vague error message:
"ERROR: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.), Inner exception: The system cannot find the file specified."
I did add a new connection string for the new table, using the database context as the connection string. As I said, everything works fine when run locally. But why is it failing when I run it on Azure?
Failing that, if I delete the database on Azure and rec-reate again, is there a fool-proof way to make Entity Framework re-create all the taables on Azure during publish/deploy?
Here's the model for the new table I'm having trouble with:
public class ImageSearchResultWrapper : ModelsBase
{
public ImageSearchResultWrapper()
: base()
{
}
[Index, StringLength(60)]
public string SearchQuery { get; set; }
public ImageResult ImageSearchResult { get; set; }
} // public class SearchResultWrapper
public class ImageSearchResultDBContext : DbContext
{
public ImageSearchResultDBContext()
: base("name=ImageSearchResultDBContext")
{
}
public DbSet<ImageSearchResultWrapper> ImageSearchResults { get; set; }
}
Here's the connection string for it:
<add name="ImageSearchResultDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-TruxWebSite-20141228220711.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />

Retrieve and use Windows Azure's connection strings?

I've configured connection strings in Azure management portal Configure->Connection Strings (linked resources):
What are these connection strings useful for?
I tried deleting the conn. strings from web.config file, so it should read from here, but it doesn't.
Is there any other way?
Basically I want these connection strings to override the connection strings in web.config to be used in production environment.
I've added the following to the Application_Start method:
var sb = new StringBuilder();
var appConfig = ConfigurationManager.OpenMachineConfiguration();
foreach (ConnectionStringSettings conStr in appConfig.ConnectionStrings.ConnectionStrings)
sb.AppendFormat("Name: {0}, ConnectionString: {1}\n", conStr.Name, conStr.ConnectionString);
throw new Exception(sb.ToString());
Here's the result:
Name: LocalSqlServer, ConnectionString: data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
I tried the above with ConfigurationManager.ConnectionStrings as well and the server (Azure) connection strings were not there.
The connection strings in the Portal allow you to override the connection strings defined in the web.config.
When you're developing locally, you probably use a database located in localhost\SQLExpress or something similar. If you deploy without having set up web.config transformation it would mean that your Web Site running in Windows Azure would still point to localhost\SQLExpress, which isn't something you would want.
The connection strings in the Portal allow you to override existing connection strings which are already defined in the web.config. If your web.config does not contain a connection string with the same name as the one configured in the portal, it will not be added and be accessible at runtime. This might be the issue you're experiencing.
To fix this, simply add a connection string to your web.config file with the same name as the one you have already added to the portal.
Update: Like I already explained in a comment, Windows Azure Web Sites does not physically modify the web.config (source), it does this at runtime. So in order to check which AppSettings and ConnectionStrings are actually available at runtime, try this:
Controller:
public ActionResult Index()
{
ViewBag.ConnectionStrings =
ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>();
ViewBag.AppSettings = ConfigurationManager.AppSettings;
return View();
}
View:
<h3>ConnectionStrings:</h3>
<ul>
#foreach (var setting in ViewBag.ConnectionStrings)
{
<li>#setting.Name: #setting.ConnectionString</li>
}
</ul>
<h3>AppSettings:</h3>
<ul>
#foreach (var s in ViewBag.AppSettings)
{
<li>#setting: #System.Configuration.ConfigurationManager.AppSettings[s]</li>
}
</ul>
After two days, I have finally managed to get it to work. I'm adding my solution here hoping that it might help someone in future.
Environment
Azure API APP (but in theory, it should work for other types of projects too)
SQL DB (hosted on Azure). It can be obviously any db
EF 6.0 - Database First Approach
Connection String is stored on Azure under Application Settings ->Connection Strings section. Image shown below
What I wanted to do
I wanted to put my connection string on Azure and like #Sandrino Di Mattia mentioned, dynamically retrieve it from there.
Steps which worked for me
Create a connectionStrings in the web.config
`
<connectionStrings>
<add name="dbConnectionStringForAzure" connectionString="Local Connection String" providerName="System.Data.EntityClient"/>
</connectionStrings>
`
Note that the providerName is System.Data.EntityClient and not System.Data.SqlClient.
Extra bit: Also, once you have published the project, you can verify that the connection string in the web.config. Navigate to projectorapiurl.scm.azurewebsites.net.
Go to Menu -> Debug Console -> PowerShell -> Edit Web.config file.
(There are other ways to get the web.config files too. Use the one you prefer.)
Note: Here you might find another auto generated connection string by Azure. It's safe to remove that as we aren't using that.
Go to Azure -> your project and Application Settings. Add the details like shown below:
Name = dbConnectionStringForAzure
Value = Provider=System.Data.SqlClient; metadata=res://*/csdlModel.csdl|res://*/ssdlModel.ssdl|res://*/mslModel.msl; Provider Connection String ='Data Source=server.database.windows.net,1433;initial catalog=database;User ID=username;Password=password;MultipleActiveResultSets=True;App=EntityFramework;'
Front the third dropdown, select CUSTOM. It's important else Azure will add System.Data.SqlClient (or any other provider depending upon what is selected) in the provider name of our connection string, which we don't want.
Save
At this stage, Azure should use this connection string on runtime. Want to verify!? do similar to what is suggested above by #Sandrino Di Mattia or in this SO post by #Shaun Luttin Retrieve the connection string of an SQL Azure database that is linked to a Windows Azure Web Site with C#.NET.
Alternatively, put the below code in any razor template:
<p>Value of dbConnectionStringForAzure :
#System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionStringForAzure"].ConnectionString
</p>
On the other hand, I have set the connection string name in my DbContext constructor.
public MyEntities() : base("name=dbConnectionStringForAzure")
{
}
Now, when I made a call to my API it dynamically used the connection stored in Azure.
Thanks to the dozens of posts and extra shots of coffee!

Categories

Resources