Class Library (.Net Framework) not supporting Entity Framework - c#

I have created a Class Project (Class Library) for Login. I have installed EF >> created models >> Created Data Context file >> Executed "enable-migration" command in NuGet Package Manager >> Executed "add-migration" command in NuGet Package Manager.
Now when I was trying to executed last step - "update-database" command in NuGet Package Manager, it threw an 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: 26 - Error Locating Server/Instance Specified)". There is no issue with connection because I repeated the same steps, but this time I used Web Project. It worked successfully.
Reason why was I doing this: I have 3 different application which uses same user authentication. I thought I can refer this class project in all 3 projects for authentication.
Am I doing something wrong? What am I missing? Or is it that Class project doesn't support EF? Is there any work around?
Edit: Class Library uses App.Config and Web Application uses Web.config.
Thank you in advance.
PS: Warning Advice for auditors - I just need answers. Please don't try to tell me that this question is duplicate, not following rules, etc. because I don't care. Let me get answer then you may block my question all you want. Till then have patients and sit quietly without making any comments.

Finally, I found solution to this.
When I install Entity Framework, EF places some default code in application's config file. As below:
Problem Code:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
Solution:
This was root of the problem I was facing. By default it was creating a local connection string for itself. I made following changes:
1.) Changed "LocalDbConnectionFactory" to "SqlConnectionFactory"
2.) Removed parameters tag completely.
So it should look like this:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />

Related

Store provider error with EF

I'm currently working on a MVC application which uses Entity Framework to interact with an Oracle Database.
Creating the edmx, adding and updating tables, all those actions are done without raising any error since I've installed all the Oracle providers I needed to make it work with .NET.
However, here's the thing : when I'm trying to run my app (which is done without errors), when the following line is executed, Visual Studio raises an error.
return PartialView("_GridViewRecruitmentPartial", model.Where(e => e.NON_ACTIVE != 1).OrderByDescending(e => e.EMPL_ID).ToList());
The error message :
The specified store provider cannot be found in the configuration, or
is not valid.
And the inner message:
Unable to find the requested .Net Framework Data Provider. It may not
be installed
I'm aware that something's wrong with EF and Oracle but can't see what. Plus, I've plenty of other projects using those 2 and everything went well.
Any guess?
I am not sure what are you using for data access. There are multiple Oracle providers... Anyway, you should probably use official Oracle Managed driver from Nuget.
When you install it from Nuget it should add itself to your web.config so everything works..
<entityFramework>
<providers>
<provider invariantName="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</providers>
</entityFramework>

Two identical generated databases with Entity Framework 6

I have build an application with Entity Framework 6, created some methods to insert an extract data from a database, and I would now like to test it for both a production- and a debugging environment.
To be sure it all works as I would like it to, the debugging database should erase all data for my tests, while my production should keep its data.
I have two projects: MyApp.Database and MyApp.Database.Test, and they each have a connection-string in their app.config-file, which the program loads as so:
public DatabaseContext() : base("name=MyDB")
{
System.Data.Entity.Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
}
and connection-string, where the database parameter set to MyProdDB and MyTestDB:
<connectionStrings>
<add name="MyDB" connectionString="Host=localhost;user id=myUser;password=myPassword;database=MyProdDB" providerName="Npgsql" />
</connectionStrings>
When I run the application, and run the tests, I get the correct connection-string for each type of database.
But I get an error when I run my tests:
42P01: relation "dbo.Tags" does not exist. A simple message, saying I have not migrated my data into my test database.
But how do I migrate it into the test database?
I tried selecting the test-project in the Package manager Console, and running the following commands:
PM> Add-Migration "Init"
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No migrations configuration type was found in the assembly 'MyApp.Database.Test'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).
PM> Enable-Migrations
No context type was found in the assembly 'MyApp.Database.Test'.
Do I need to specify my own DbContext class for MyApp.Database.Test which is almost a replica of MyApp.Database?
If you don't need data in your DEV environment, just drop database. You use CreateDatabaseIfNotExists, so it will create new database with up-to-date schema.
More then it, you can configure your initializer in config file. Use CreateDatabaseIfNotExists inializer on PROD and DropCreateDatabaseIfModelChanges on DEV. So if model will change, you will have to use migrations on PROD, but DEV will just drop database and create again.
Example:
<contexts>
<context type="Elmah.SqlServer.EFInitializer.ElmahContext, Elmah.SqlServer.EFInitializer">
<databaseInitializer type="Elmah.SqlServer.EFInitializer.ElmahDatabaseInitializer, Elmah.SqlServer.EFInitializer" />
</context>
</contexts>
or look here

How to use Entity Framework 6 to migrate database to local SQL Server from network server

I got a ASP.NET MVC 5 project which is already published in a server. But I have to extend it. Thus I'm trying to make local development environment with local database. I don't want to loss any data which is already working. As this is huge project. So all model and controller is done.
I'm also not an expert in ASP.NET world. After searching for a while I found there is way called code first approach.
As I have all the model so I'm assuming it should be able to make all local database in my machine.
The actual project connection strings looks like this:
<connectionStrings>
<clear />
<add name="Name.DataSourceConnectionString"
connectionString="Data Source=test.test.com;User ID=myUser;Password=myPass"
providerName="System.Data.SqlClient" />
</connectionStrings>
So for local machine I updated as:-
<connectionStrings>
<add name="My TEST"
connectionString="Data Source= 192.168.1.12;Initial Catalog=MyDB;Persist Security Info=True;User ID=dev;Password=dev"
providerName="System.Data.SqlClient" />
</connectionStrings>
I got project source and build and launch the service locally. When I try to logged in I get following error:-
The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Note that same login is working fine in server.
Then I follow the link.
In package management console I insert command enable-migrations and then update-database -Force. I got following 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I have SQL Server 2012 Express installed. I suspect my connection string is not defined correctly. How do I define it? Also any suggestion how to have local set-up development environment for working ASP.NET service?
connectionString="Server=myip;Port=3306;Database=mydatabase;Uid=admin;Pwd=password;"
you could try this maybe you missing port and select database don't know how many database is configure in your mssql server.
Code First, despite its name, can either create a new database or work with an existing database. However, and this is key, it cannot both create and manage tables and work with existing tables in the same database (at least not with the same context).
You can have multiple contexts, but they must be entirely segregated, i.e. they can't reference entities tracked by a different context or they'll attempt to take control of those entities away from that other context.
Long and short, if you have an existing database that you need to work with, Code First migrations are pretty much out the window. You can create new entity types, but you'll need to create the tables for them manually in your database.
As far as just get a local copy goes, though, all you need to do is take a backup of the production DB and restore it locally. It really has nothing to do with Entity Framework or MVC.

The provider did not return a ProviderManifestToken string Entity Framework

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
Inner Exception: {"The provider did not return a ProviderManifestToken string."}
I've searched other threads as there are many with similar errors, but I cannot seem to find a solution.
I am using VS2012 Professional and SQL Server 2012. I am able to connect to the server using Server explorer using windows authentication. I am building a webforms application with multiple tiers. One of them containing my Entity framework tier which contains my Context class.
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="MYSQLSERVER"
providerName="System.Data.SqlClient"
connectionString="Data Source=myComputer\MYSQLSERVER;Trusted_Connection=true"></add>
</connectionStrings>
</configuration>
This is what the app.config in my Entity Framework class library layer looks like.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
Also, I have tried changing the app.config defaultConnectionFactory type to
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
but it did not change anything.
I am not really sure what any of the changes I am making even mean which worries me. Sure I could of found the solution online and fixed my issue, but I would really like to understand the web.config and what this all means. On top of finding a solution to this problem, can anyone point me in the right direction to learning web.configs?
Thank ahead for your help.
In my case, it was my SQL Server instance that was not running. I simply started the service and everything worked fine. Hope this helps someone down the road.
I also faced to this error and I solve that downgrading these NuGet packages
MySql.Data - 6.9.12
MySQL.Data.Entity - 6.8.8
this is my reference URL which I referred
Well I fixed it.
Just needed to put "." for localmachine in the data source as follows:
<add name="MYSQLSERVER"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\MYSQLSERVER;Trusted_Connection=true"></add>
</connectionStrings>
Here's another possible cause:
I have both my (ASP.NET) HTTP server and MySQL/Aurora server on AWS (understood that AWS was not part of the OP's comments).
My desktop's (actually, our building's) IP was whitelisted in the MySQL/Aurora server's security group, so everything worked perfectly for development.
But the ASP.NET server's IP was not whitelisted for the MySQL/Aurora instance, thus the ASP server's EF connection request was being rejected, and that was causing the exception noted at the top of this thread.
Esoteric, but maybe this helps someone.
For those getting this recently, in updating to MySql.Data 8.0.19 you also have to update your references for EntityFramework, Oracle changed the package, it's now MySql.Data.EntityFramework instead of MySql.Data.Entity or MySql.Data.Entities. Props to David Sekar: https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken
For me, It was all of the below.
1. DB not allowed to connect to my dev environment. May be firewall restrictions.
2. Connection string had wrong credentials for the DB.
So generally speaking, incorrect connection string.
i meet this problem when i try to connect to mysql, the reason is that i forget to add the "password" in "connectionStrings"
In my case the paramter was v12.0, I changed to v11.0 and it is working
I had the same problem, reinstalling Npgsql with the package manager did the trick.
Seemed to be a versionning problem.
For me, it was using double backslash between the server and the instance, such like .\SQLExPRESS;...etc.
The correction was to use .\SQLEXPRESS
hope it helps someone.
I often forget why this error comes often. For me its usually I have changed credential of the database and did not change the same on the code section.
Just in case if I come here again to remind myself.
..and FINALLY(?!?) don't forget to build your project with 'Prefer 32-bit' checked as this will eliminate the KNOWN BUG which generates this error message (which has the inner exception message = 'Arithemtic overflow')

EF 5 Migrations cannot connect to our database even though it does just fine at runtime

We have three projects.
Company.Domain (class library)
Company.PublicWebsite (MVC3 Web Application)
Company.InternalWebsite (MVC3 Web Application)
The two website projects have reference to Company.Domain.
Our EF 5 DbContext lives in Company.Domain.Data.EntityFramework and it looks like this:
using System.Data.Entity;
using Company.Domain.Data.EntityFramework.Entities;
namespace Company.Domain.Data.EntityFramework.
{
public class CompanyEntities : DbContext
{
public DbSet<Notification> Notifications { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<ReportSection> ReportSections { get; set; }
public DbSet<ReportPage> ReportPages { get; set; }
// brevity brevity
}
}
We have enabled migrations and successfully used the tool in the past so I'm not sure why we are having issues now. Our migrations configuration lives in Company.Domain.Data.EntityFramework.Migrations and looks like this:
namespace Company.Domain.Data.EntityFramework.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Company.Domain.Data.EntityFramework;
public class Configuration : DbMigrationsConfiguration<CompanyEntities>
{
public Configuration()
{
MigrationsDirectory = #"Data\EntityFramework\Migrations";
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CompanyEntities context)
{
// empty at the moment
}
}
}
We then have an App.config file in the root of the Company.Domain project and it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="CompanyEntities" providerName="System.Data.SqlClient" connectionString="Data Source=devsql;Initial Catalog=CompanyEntities;uid=XXXXX;pwd=XXXXX;MultipleActiveResultSets=True;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Our database lives on another server on the network. I'm able to connect to it in SQL Server Management Studio and our applications are able to connect at runtime just fine. However, when I try to run add-migration or even update-database I get the following error:
http://content.screencast.com/users/Chevex/folders/Snagit/media/80fbfd6a-4956-407f-b88f-d5a53a9e5feb/03.21.2013-10.25.png
System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: 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.
I've even reverted my changes to the model and then ran update-database just to see if it would say 'database is on latest migration' but I still got the above error. I've poured over the connection string in App.config over and over. I cannot figure out why migrations won't connect but both of our website projects work just fine at runtime. Migrations have worked in the past. Below are the migrations in solution explorer compared with those found in the __MigrationHistory table in the database.
http://content.screencast.com/users/Chevex/folders/Snagit/media/7abeaa46-ff0f-4817-a0d7-1adb086e8f0c/03.21.2013-10.30.png
http://content.screencast.com/users/Chevex/folders/Snagit/media/3c6ac54d-f63d-417f-9253-39b6a8fea85d/03.21.2013-10.32.png
It looks like I should be able to run update-database and have it tell me that it is up to date, but I get that error instead.
As I understand it, migrations shouldn't be paying any attention to our two website projects when I'm running migrations commands, but I poured over their Web.config files as well just in case. The connection strings are identical to App.config.
Edit:
I've even tried completely uninstalling and removing the EF 5 package from the projects and reinstalling. Same issue >:(
Did your start project contains web.config or app.config as EF use the start project as source of the connection string
OK, so that didn't work for me at first :(
Then after a cup of coffee and adding StartUPProjectName to it, it did!
Try:
Update-Database -StartUpProjectName MYPROJECT.NAME -Script
Try to point it to a start Up project where you web.config/app.config lives
If you get the help for enable migrations in the Package Manager Console
Get-Help enable-migrations -detailed
You can find this documentation for the -StartupProjectName option:
-StartUpProjectName
Specifies the configuration file to use for named connection strings. If
omitted, the specified project's configuration file is used.
The doc it's a little confusing, but it means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config).
If you're creating a web app, most probably the connection string will be in its web.config, so you have to specify the web app project. If it's other kind of project, the connection string will be in an app.config file of a class library or whatever, and you'll have to specify that project.
Besides it's recommended that you use a constructor for your DbContext class that specifies the name of the connection string, i.e.
public class CompanyEntities : DbContext
{
public CompanyEntities()
:base("ConnectionStringName")
{
...
}
....
}
In this way you don't depend on default connection strings, which may be confusing.
You say you can connect via SQL Management Studio, but my guess is you use Windows Authentication for that, and not the uid=XXXXX;pwd=XXXXX; supplied in your connection string.
Try to get Management Studio to connect using that userid and password.
Also, that account might be locked out (if it is an Active Directory account).
This sounds eerily like a problem a client of mine had. It had to do with something having mucked up the DbProviders section of machine.config. He put the details here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/f2a19487-6d38-4a79-a809-d3efe4c9d9fe (it's the Adam Scholz answer to his boss' question. :) )
Julie
May be this is solved already but i got it solved by setting the start up project in my solution to the entity dll project ( having app.config file ). I did set the "Default project" in Package Manager Console window to the correct entity dll project but that did't work. For details
Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException
system-data-entity-core-providerin
If your solution has multiple projects, try setting the Startup Project for the solution to the project that contains the Web.Config or App.Config file that contains the settings for EF.
I had a solution with a Web project and seperate project (Data.Models) for my models. All was well until I added a console application to the solution. As soon as I set that to be the startup project, EF Migrations would fail.
Also, if multiple projects in the solution have migrations enabled, always run the Update-Database on each project after you do a Add-Migration. My web project had a pending migration, and the migrations failed weirdly on the second project because of the pending migration in the first.

Categories

Resources