All DbSets are empty? - database

In my solution I got a DataAccess project which has the following connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\LM.DataAccess.mdf;Initial Catalog=LM.DataAccess;Integrated Security=True" providerName="System.Data.SqlClient" />
It has a repository which can access the database just fine WHEN being run by the DataAccess project itself.
I'm trying to access the repository from another project in the solution - however whenever I'm in the repository (from running this project) all the dbsets on the dbcontext are empty.
What could be the reason of this issue?

Related

Web.Config SQL Connection

My Web.Debug.Config code:
<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=DESKTOP-RTOUFCH\\SQLEXPRESS;Database=NextLevel;Integrated Security=True;" />
</connectionStrings>
My CSharp code:
using System.Configuration;
using System.Web.Configuration;
using System.Data.SqlClient;
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["NextLevel"].ConnectionString;
I keep getting a null reference error.
When I attempt to iterate through the connection strings, it finds one named "LocalSQLServer" which is not even in my web.Debug.config file.
What am I doing wrong?
That last comment by ThomasArdal:
I would also suggest you to publish web.config, web.debug.config, and web.release.config. If you have those files.
allowed me to figure out my problem.
I was updating web.debug.config when I should have been updating web.config.
<connectionStrings>
<add name="NextLevel"
providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=NextLevel;Integrated Security=True;" />
</connectionStrings>
Check with this instead!

How to fix this issue? Cannot open database '' requested by login. the login failed

I am running this command on Nuget and will show web.config for my connection String. This apps is a web and uses Individual User Account, where namespace like AspNet.Identity are used. The error is 'Cannot open database 'eNtsaRegistration" requested by the login. The login failed. Login failed for user'Mandela\Gcobanim".
Scaffold-DBContext "Data Source=(LocalDb)\MSSQLLocalDB; Initial Catalog=eNtsaRegistration;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
<add name="eNtsaRegistration" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-eNtsaRegistration-20200304090520.mdf;Initial Catalog=aspnet-eNtsaRegistration-20200304090520;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Scaffold-DBContext "Data Source=(LocalDb)\MSSQLLocalDB; Initial Catalog=aspnet-eNtsaRegistration-20200304090520;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

SSDT Unit Test:. An error occurred while SQL Server unit testing settings were being read from the configuration file

I created a database project in Visual Studio 2013 professional. Then added a unit test by right click on one of the stored procedure and select Create Unit Tests. Selected to create a new VB test project. Then right click on the newly created test project and select SQL Server Test Configuration, choose localdb database and configured the project that need to be deployed.
Rebuild the solution, Run All tests (two tests). Tests always fail with this error:
Message: An error occurred while SQL Server unit testing settings were being read from the configuration file. Click the test project, open the SQL Server Test Configuration dialog box from the SQL menu, add the settings to the dialog box, and rebuild the project.
StackTrace:
at Microsoft.Data.Tools.Schema.Sql.UnitTesting.SqlDatabaseTestService.OpenProcessConfig()
at Microsoft.Data.Tools.Schema.Sql.UnitTesting.SqlDatabaseTestService.DeployDatabaseProject()
at *************.Tests.SqlDatabaseSetup.InitializeAssembly(TestContext ctx) in C:\Projects*********************.Tests\SqlDatabaseSetup.vb:line 15
It seems to be that the app.config that is get generated by VS 2013 is empty. I did some research online and lots of try and error and came with the following app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="system.data.localdb" type="System.Data.LocalDBConfigurationSection,System.Data,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"/>
<section name="SqlUnitTesting_VS2013" type="Microsoft.Data.Tools.Schema.Sql.UnitTesting.Configuration.SqlUnitTestingSection, Microsoft.Data.Tools.Schema.Sql.UnitTesting, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</configSections>
<system.data.localdb>
<localdbinstances>
<add name="(localdb)\ProjectsV12" version="12.0" />
</localdbinstances>
</system.data.localdb>
<SqlUnitTesting_VS2013>
<DatabaseDeployment DatabaseProjectFileName="..\..\..\Database_Project_Name\Database_Project_Name.sqlproj"
Configuration="Debug" />
<DataGeneration ClearDatabase="true" />
<ExecutionContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=Database_Name;Integrated Security=True;Pooling=False;Connect Timeout=30"
CommandTimeout="30" />
<PrivilegedContext Provider="System.Data.SqlClient" ConnectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=Database_Name;Integrated Security=True;Pooling=False;Connect Timeout=30"
CommandTimeout="30" />
</SqlUnitTesting_VS2013>
</configuration>
Now I get the following error:
Failed to deploy database project C:\Projects\Database_Project_Name\Database_Project_Name\Database_Project_Name.sqlproj. But this seems to be because my database depends on other databases and I need to deploy the other database with my database.

Entity Framework Provider Configuration

I'm using EF 6.1 Code First. I'm programmatically configuring the connection string at runtime like:
myContext.Database.Connection.ConnectionString = "Data Source=(localdb)\v11.0;Initial Catalog=MyDb;Integrated Security=True;"
This works fine, but only if I keep some boiler plate connection information in my app/web.config:
<connectionStrings>
<add name="MyDb" connectionString="Data Source=NOTUSED;Initial Catalog=NOTUSED;" providerName="System.Data.SqlClient" />
</connectionStrings>
I suspect this is because I'm not providing the provider information. I am specifying the provider and defaultConnectionFactory sections (SQL Server / LocalDbConnectionFactory), but it doesn't seem to care:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
If I remove the connection strings section, it attempts to attach to a mdf file that doesn't exist:
System.Data.SqlClient.SqlException: Cannot attach the file 'C:\My
Project\App_Data\MyDb.mdf' as database MyDb.
Normally, the localdb connection string results in a path to c:\users\my_user\MyDb.mdf. So it seems like it's not using the LocalDb factory unless I've got the connection string section in my .config file.
How can I specify - on a per context basis - the providerName information that EF is getting from that connection string node? Or am I barking up the wrong tree here?
This may have something to do with the way you are constructing your connection. If you are using the default constructor on the DataContext, then it will attempt to find your connection string from the config file:
MyDbContext myContext = new MyDbContext() <- this uses the default constructor
myContext.Database.Connection.ConnectionString = "_conn_str_"
If you pass the connection string in the constructor, then you should not need the config file entry:
using (MyDbContext myContext = new MyDbContext("_conn_str_")) {
// the above line should not need an entry in the config file
}
Hope this helps.

Running MSTest with tests against different databases

I would like to ask what is the best way to execute a setup like the following:
We have tests suite that is compiled, and in the app.config file I have 6-7 different connection strings to different databases. I would like to run the tests suite against every connection, and I hoped to parametrize in some way this process - something like setting the name of the connection and passing it on to the testrun as a parameter. What I figured out so far is that I can use different localconfigrun files and through deployment items I can feed a xml/txt file with the required value, but is there a nicer and lighter solution? I need just to send a key/value pair or simple string to configure my base class inside the test suite.
I am using tfsbuild but I can use the mstest thrugh other environments as well (pure msbuild, etc.)
Thanks in advance.
I have had a similar issue. This is what I did:
My app.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ConenctToInputDB" value="InputDev" />
<add key="ConnectToOutputDB" value ="OutputDev"/>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<add name="LocalConnection" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputDev" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputCert" connectionString="YOUR CONNECTION STRING HERE"/>
<add name="OutputDev" connectionString="YOUR CONNECTION STRING HERE/>
<add name="OutputCert" connectionString="YOUR CONNECTION STRING HERE" />
<add name="InputProd" connectionString="YOUR CONNECTION STRING HERE/>
<add name="OutputProd" connectionString="YOUR CONNECTION STRING HERE" />
</connectionStrings>
In this secenario, I have 2 dbs I connect to and I have 3 different connection strings for each (Development, Certification and Production)
Add this to the bottom of your project file (right click on the project and unload it). Make sure you add it before the </project> tag. (You will need to install the MSBuild Community Tasks for this to work. They can be downloaded for free from: http://msbuildtasks.tigris.org/ (Make sure you get a nightly build))
<PropertyGroup>
<!--Import the MSBuild community tasks so we can update xml-->
<MSBuildCommunityTasksPath>C:\PathToMSBuildCommunityTasks\MSBuildTasks</MSBuildCommunityTasksPath>
<SubstitutionsFile Condition="'$(Configuration)' == 'Debug'">DevAppSettings.xml</SubstitutionsFile>
<SubstitutionsFile Condition="'$(Configuration)' == 'Cert'">CertAppSettings.xml</SubstitutionsFile>
<SubstitutionsFile Condition="'$(Configuration)' == 'Prod'">ProdAppSettings.xml</SubstitutionsFile>
</PropertyGroup>
<Import Project="C:\PathToMSBuildCommunityTasks\lib\MSBuildTasks\MSBuild.Community.Tasks.Targets" />
<Target Name="AfterBuild">
<!--Update the app config to have the correct environment paths-->
<Message Text="Updating $(MSBuildProjectName) config to $(Configuration)" Importance="high"></Message>
<XmlMassUpdate ContentFile="$(OutDir)\$(MSBuildProjectName).dll.config" SubstitutionsFile="..\..\$(SubstitutionsFile)" />
</Target>
This will replace the <appSettings> section of the app.config file based on the current configuration. You will need to make new new configurations (I called them Cert and Prod).
The last step is to make a file for each configuration (I called them DevAppConfig.xml, CertAppConfig.xml, ProdAppConfig.xml)
In each file should look like this (this one is for the Certification Configuration):
<?xml version="1.0" encoding="utf-8"?>
<!--This file is used by the build files to merge in solution wide app settings
Some projects contain files that have an AppSetting section (usually in App.config). Those projects have
and AfterBuild event in the project file that substitues this xml tree over the the normal xml tree.-->
<configuration xmlns:xmu="urn:msbuildcommunitytasks-xmlmassupdate">
<appSettings>
<add xmu:key="key" key="ConenctToInputDB" value="Cert"/>
<add xmu:key="key" key="ConnectToOutputDB" value="ESPCert"/>
</appSettings>
</configuration>
all of this, once installed will make the file that is output by app.config be auto changed based on the configuration you are compiling. This code works for both compiling in the IDE and in Team Build.

Resources