Message When Using Entity Framework in an MVC Application - entity-framework

I add ADO.net entity model to an ASP.NET MVC application and the database tables appear correctly after writing the connection string.
But when I run I see this message.
My table name is ETAConfiguration:
My database is in another version not SQL Server Express so I click no. Then I get an error in a normal LINQ statement:
var context = new MyOwnTaxDatabaseEntities();
List<ETAConfiguration> configs = context.ETAConfigurations.ToList();
The error occurs on this line:
List<ETAConfiguration> configs = context.ETAConfigurations.ToList();

Related

Convention for set Database.SetInitializer<> in Entity Framework code-first

I am trying to develop my first Entity Framework code-first approach. I am little bit confused regarding Database.SetInitializer<> -
Can I set multiple initializer ? i.e.
Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<Context>());
Database.SetInitializer<Context>(new DropCreateDatabaseIfModelChanges<Context>());
If I use only CreateDatabaseIfNotExists initializer, and later I change database server in connection string, then will the database be created on new server?
No you cannot set multiple initializer. Initializer Only insert data once in database after database created, and database creation script(internally) runs only when you will access any record of any table first time.
And before creating database EF always check first ,the database specified in connection string is present in database server. If database is not there then it will create.

Accessing DB2-LUW 10 with entity framework 6

I am developing an application in which the database is selected by the end user at runtime. The database can either be on a MS SQL server or an IBM DB2 server. I am currently using IBM DB2 10 Express-c on a windows server for testing. I am developing using Visual Studio 2013 C# and Entity Framework 6. I have installed the EntityFramework.IBM.DB2 Nuget package for the DB2 support. I am using reverse-engineer code-first against an existing SQL server database to generate my base code. The application works fine against a SQL Server database.
I am using System.Data.Common.DbProviderFactories.GetFactory to generate the provider.
System.Data.EntityClient.EntityConnectionStringBuilder connectString = new System.Data.EntityClient.EntityConnectionStringBuilder(a_Connection);
System.Data.Common.DbConnection conn = System.Data.Common.DbProviderFactories.GetFactory(connectString.Provider).CreateConnection();
conn.ConnectionString = connectString.ProviderConnectionString;
LB500Database = new LB402_TestContext(conn, true);
a_Connection is provider=IBM.Data.DB2;provider connection string="Database=LISTBILL;User ID=xxxx;Password=yyyy;Server=db210:50000"
and is being parsed correctly by the EntityConnectionStringBuilder.
I then try to access a table in the database with
LBData500.LB_System oneSystem;
System.Linq.IQueryable<LB_System> allSystem = LB500Database.LB_System.Where(g => g.DatabaseVersion == databaseVersion && g.CompanyID == companyID);
I get an invalid operation exception "Sequence contains no matching element" which means that no elements are returned. If I remove the Where so that all rows are returned (there is one in the table) and try to enumerate the result set using the VS debugger I see the message:
"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe."
I am not using multi-threading. I am not inside the OnModelCreating.
Just changing the connect string to point to SQL server works fine, so I think my basic approach is sound. If I were getting some kind of error back from the server I would have something to go on. I can run the query from inside Visual Studio, so I have connectivity.
Any pointers would be appreciated.
UPDATE:
I turns out the EF objects were generated using EF5 and the EF6 runtime was being used. I regenerated the EF objects using EF6 reverse engineer code first. I can now connect to the database and get an error message:
"ERROR [42704] [IBM][DB2/NT64] SQL0204N \"DBO.LB_SYSTEM\" is an undefined name."
The schema in the DB2 database is the same as my userid (in this case, not always). I added the CurrentSchema=xxxx to the provide connection string, but EF is still passing dbo as the schema name.
Now I need a way to change the schema name at run time. I saw a link to codeplex EFModelAdapter (http://efmodeladapter.codeplex.com). So I may give that a try.
Update2 After looking through EFModelAdapter, I decided to take a different route. Since I only need database access and not schema management, I decided to go with Dapper (https://github.com/StackExchange/dapper-dot-net). This works great for what I need and allows me to change the schema name when accessing DB2 databases.
As per my Update 2, Entity Framework was a little overkill for what I needed. I switched to dapper https://github.com/StackExchange/dapper-dot-net and I am working fine against multiple DBMSs.

Entity Framework 6.0: how to use edmx context when connection is configured in code?

I use Visual Studio 2013, Entity Framework 6.0.
So far I had the connection string in the app config, and that worked.
The DB context was created by adding a "ADO .Net Entity Data Model" with the option "EF designer from database"
But now I need to move it to code since it will depend on user input.
I followed this example for the connection string and my DB successfully connects
http://msdn.microsoft.com/library/vstudio/bb738533
But now I need to use the connection with my database context, and I can't get this done.
Say my data model is named MyDB, then I had under MyDB.edmx the MyDB.Context.cs, and there the MyDBEntities class derived from DbContext.
I re-created the data model, but this time did not select the option to store the connection string in the app config. First difference in result is that MyDBEntities is now only called Entities. Why that?
I see that the DbContext has a constructor which accepts a EntityConnection.
I was able to create a DbContext with the connection, but that is not linked with the datatypes under MyDB.edmx. And MyDBEntities ( or just Entities after the change ) has no constructor accepting an EntityConnection.
So how can I use the generated edmx model but configure/open the connection at runtime?
Found it. Ok so in EF 6.0 the DbContext no longer has a constructor that accepts a connection, but there is one that accepts a connection string.
Just modify the generated code and add the following constructor:
public Entities(String connectString) : base(connectString) { }
Then directly pass the connection string and it will work.

Linq-to-SQL with SQL Server Compact Edition

I am working on a small application that is using Linq-to-SQL to access a SQL Server database. The requirement is to write tests using SQL Server CE to test the application.
In the past, I created tests using SQL Server CE with Entity Framework and it's straight forward due to support of SQL Server CE in Entity Framework that allows .sdf file creation based on the entities.
Is there any way to achieve the same for Linq-to-SQL, too? To be very specific, I want to achieve something like this using Linq-to-SQL:
System.Data.Entity.Database.DefaultConnectionFactory =
new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (var sqlCeContext = new EntityFrameworkContext())
{
sqlCeContext.Database.Create();
}
Yes, the DataContext class has a CreateDabase method, that you can use. http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx

MultipleActiveResultSets for postgresql and ado.net entity data model

Im using visual studio, postgresql database and ado.net entity data model. In the connectionstring, Im unable set MultipleActiveResultSets=True.
Usually when I connect to sql server with MultipleActiveResultSets=True, it works fine. but i cannot set the same with postgresql database.
When I use this, I got the following error
There is already an open DataReader associated with this Command which
must be closed first.
How do I solve this problem.
Multiple Active Result Sets (MARS) is a feature introduced in SQL Server 2005 and is not available in other database systems like postgres so you won't be able to turn it on in the connection string.
The error you are facing is an outcome of trying to perform two queries on one open data reader. When using ie Entity Framework this usually happens when you have Lazy Loading turned on and the lazy properties are loaded in the same reader as the parent entites. For example a code similiar to this could produce this error:
var users = context.Users.Where(u => u.FirstName.StartsWith("Ha"));
foreach (var user in users)
{
Console.WriteLine(user.Address.StreetName);
}
In the 1st line no data is fetched as we only have prepared a Linq query. When we start the foreach a DataReader is opened and collection of users that meets the our conditions is queried but the reader is not closed. Then inside foreach we reach to the Address property of User which is lazy loaded. This lazy load causes a query execution on the same open DataReader and that's when the exception occurs. If i wanted to get rid of the error i could simply add a ToList() (or anything causing the query to perform) to the end of the line like this:
var users = context.Users.Where(u => u.FirstName.StartsWith("Ha")).ToList();
Hope this will help you.
Just add preload reader=true in your postgresQL connection string.
<connectionStrings>
<add name="PostgresQL Npgsql" connectionString="server=srvubuntu01;user id=postgres;password=postgres;database=WinUnified;preload reader=true" providerName="Npgsql" />
</connectionStrings>