EF7 "Invalid Object Name 'xyz'" when manually scaffolding existing database - entity-framework

I've published a DB using an SqlDatabase Project.
I've manually created POCO classes, as well as a Db context to match the published database.
Whenever I try to execute an EF statement, valid SQL Query is generated, but I receive the error
An exception occurred in the database while iterating the results of a query.
System.Data.SqlClient.SqlException (0x80131904): Invalid object name '[xyz]'
The properties on the EF class match exactly type/nullable/name/etc in the database. The query generated, when run manually works fine.
Any help appreciated.

Related

Postgres EF Migrations "3F000: No schema has been selected to create in"

I am attempting to execute an initial database creation migration using entity framework core against a postgres database.
The problem I am having is that I wish to create the tables under a custom schema.
I have managed to create an initial migration with no problems but when I attempt to "update-database" the migration fails with the following error.
Npgsql.PostgresException (0x80004005): 3F000: no schema has been selected to create in
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<g__ReadMessageLong|0>d.MoveNext()
Having initial looked into the issue I assumed this was simply because the schema was not being set in the context.
To get around this I set added the following code to the DbContext
protected override void OnModelCreating(ModelBuilder builder)
{
//Set the default schema
builder.HasDefaultSchema("ConfigStore");
//Continue with the call./Migrate
base.OnModelCreating(builder);
}
I still get the same error when running update-database.
I checked the initial migration Up() method and can clearly see the following code:
migrationBuilder.EnsureSchema(name: "ConfigStore");
The migration creates the database but nothing else so I assume the problem here is that the schema is not being created after the database which is then subsequently causing the table creations to fail.
The question I have is how do I fix this?
Can I execute some custom sql AFTER the database has been created but before the tables? Is there something I can do to get EnsureSchema() to create the schema first?
Thanks in advance
Would you believe it. Hours and hours trying to figure it out and 10 minutes after posting on stack overflow I find the solution....
The problem was the initial connection string. I had defined the connection string as follows:
Server=127.0.0.1; port=5432; user id=XXXX; password=XXXX; database=Test; pooling=true; SearchPath=ConfigStore
The problem was the search path. Apparently EF Migrations creates the database perfectly with this connection string but then attempts to access the tables before creating the schema causing the error reported. Removing the search_path from the connection string resulted in the schema being created first, then the tables. Odd - but hey it works.
I have my custom schema kernel. The following search path helped me to resolve the issue
"Host=localhost;Database=test08;SearchPath=kernel,public;Username=postgres;Password=strongPa$$123;"

ASP.NET Identity Model First fails because of renamed AspNetUserRoles columns

Like several others I have tried to implement ASP.NET Identity Model First. Everything works fine once you have tried, errored, fumed, searched and resolved.. I thought.
See also:
ASP.NET Identity with EF Database First MVC5
http://danieleagle.com/blog/2014/05/setting-up-asp-net-identity-framework-2-0-with-database-first-vs2013-update-2-spa-template/
Course of action, summarized:
Created default project (MVC5)
Create database
Update connectionstring in the web.config
Run website, register: tables get created
Create EF Model (edmx)
Import Identity tables (everything fine up to this point)
Modified xxx.Context.tt to inherit from IdentityDbContext
Generate database script (trouble starts here)
I have solved the issues that appeared (up to the latest step). For completeness I will describe them.
Using the default Identity context
Everything works fine: tables get created, I can Register and login. This is however not the situation I want: I want to use a Model First approach.
Using the custom, model first context using the EF connectionstring
Modifying the CreatePerOwinContext so that it uses my Model First context:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(CustomModelFirstDbContext.Create);
And the ApplicationUserManager so that it uses the Model First context:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<CustomModelFirstDbContext>()));
Results in:
Server Error in '/' Application.
The entity type ApplicationUser is not part of the model for the
current context.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The entity type
ApplicationUser is not part of the model for the current context.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: The entity type ApplicationUser is not
part of the model for the current context.]
Using the "normal" connectionstring with the custom, Model First context
An exception of type
'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException'
occurred in WebApplication1.dll but was not handled in user code
Additional information: 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.
So, I figured I needed the default Identity context to use Identity, and use the custom Model First context for everything else. Not the preferred solution, but acceptable.
Rolled everything back
Import Identity tables from database
(Optional) Created entities via the Model First approach
Generated database script
Both the normal project and a quick sanity check test project have the same problem with the AspNetUserRoles table. That is a junction table, and when importing it in the EF designer, everything is OK. You won't see it since it is a many to many relationship, and when inspecting the association between AspNetRole and AspNetUser it looks good.
Designer and mapping details:
However, when generating the sql script, EF modifies the keys.
Designer and mapping details:
Generated SQL script:
-- Creating table 'AspNetUserRoles'
CREATE TABLE [dbo].[AspNetUserRoles] (
[AspNetRoles_Id] nvarchar(128) NOT NULL,
[AspNetUsers_Id] nvarchar(128) NOT NULL
);
GO
In EF, you can't change the names of the mappings in the designer (thread on social.msdn.microsoft.com).
Subsequently the creation of a new user wil fail, using the originally created context because the junction table contains the wrong columns:
Server Error in '/' Application.
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'RoleId'.
Invalid column name 'UserId'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'UserId'. Invalid column name 'UserId'. Invalid column name 'UserId'. Invalid column name 'RoleId'. Invalid column name 'UserId'.
Source Error:
Line 89: {
Line 90: var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
Line 91: IdentityResult result = await UserManager.CreateAsync(user, model.Password);
Line 92: if (result.Succeeded)
Line 93: {
What is the solution? Are there any alternatives than trying to change the generated script, or moving to Code First?
If you in the begginning and db is still empty than
I believe the easiest workaround is:
Create EF Model(edmx).
Right click on model "Generate Database from model".
It will create DDL file (snippet below)
Replace all wrong "AspNetUsers_Id" and "AspNetRoles_Id" for correct values.
Right click "execute".
Works for me.
-- Creating non-clustered index for FOREIGN KEY 'FK_AspNetUserRoles_AspNetUser'
CREATE INDEX [IX_FK_AspNetUserRoles_AspNetUser]
ON [dbo].[AspNetUserRoles]
([AspNetUsers_Id]); //replace for UserId
Happy coding!

Entity Framework 6 Code First Migration's ContextKey

Now i'm using EF6 Alpha, and when using migration, it will add a new migration log into the __MigrationHistory table.
In EF6, The __MigrationHistory table has a new column called "ContextKey". After testing, I found there are two default "ContextKey" value:
The full name of DbContext's derived class.This happens when i run the code:
Database.CreateIfNotExists();
The full name of DbMigrationsConfiguration's derived class. This happens when i run the code:
public ArticleDbContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ArticleDbContext, ArticleConfiguration>());
}
The first time i run the application, "Database.CreateIfNotExists();" create a new database for me, also all tables that map to the models defined in ArticleDbContext, and then add a __MigrationHistory row which ContextKey's value is "Module.Article.Model.ArticleDbContext".
And then "Database.SetInitializer(new MigrateDatabaseToLatestVersion());" will be runned, this code will generate a new ContextKey "PowerEasy.Module.Article.Migrations.ArticleConfiguration". Migration query the __MigrationHistory table with this ContextKey and find out there's no data. So again it will create all tables that map to the models defined in ArticleDbContext, but the tables are already exist in the database, so an exception will be throwed, and tell me "the table XXX is already existed".
How can i solve this?
You should not mix Migrations and the Database.CreateIfNotExists method (or any of the initializers built on top of it). Migrations will take care of creating the database if it does not already exist.
As an alternative to the Migrations initializer, you can also apply migrations using the DbMigrator.Update method. This is useful if you want to create/update the database before it would otherwise be triggered by the initializer.

Open JPA : An error occurred while parsing the query filter 'MY_QUERY' Error message: No field named "accessAuthorizationVs" in class "MyEntityClass"

I have configured it in my Rational Software Architect 8.0.4, by enabling the JPA 1.0 facet. It autogenerates almost all my entity classes except for the id's. So I manually add them. I am trying to query a simple table APP_USER that has one-to-many relation to ACCESS_AUTHORIZATION table. See below for the configurations and entity classes.
When I try to execute a simple named query which is
SELECT a.accessAuthorizationVs, a.empName, a.userCnum FROM AppUserEntity a WHERE a.userCnum = :userCnum
It throws an exception
**org.apache.openjpa.persistence.ArgumentException: An error occurred while parsing the query filter "SELECT a.accessAuthorizationVs, a.empName, a.userCnum FROM AppUserEntity a WHERE a.userCnum = :userCnum". Error message: No field named "accessAuthorizationVs" in class "class com.xxx.xxx.xxx.services.integration.entity.AppUserEntity".**
at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.parseException(AbstractExpressionBuilder.java:118)
at org.apache.openjpa.kernel.exps.AbstractExpressionBuilder.traversePath(AbstractExpressionBuilder.java:284)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getPath(JPQLExpressionBuilder.java:1382)
at org.apache.openjpa.kernel.jpql.JPQLExpressionBuilder.getPathOrConstant(JPQLExpressionBuilder.java:1337)
Here's a snapshot of my persistence.xml:
Can anyone guide me what I am doing wrong here? The field by that name is clearly defined in my entity class. Also I would like to mention that I had to enhance the classes[followed this] as there was an earlier error about classes not being enhanced.
When you create a named query in OpenJPA, remember that you are writing JPQL, not native SQL. The syntax is similar, but a little different.
In this case, I suggest changing your named query to the following:
SELECT a FROM AppUserEntity a WHERE a.userCnum = :userCnum
This will return an object of the AppUserEntity class which will include the set of AccessAuthorizationV objects (lazy loaded by default).
For more details, see the JPQL Language Reference.

Calling DB2 stored procedure from Entity Framework

I am trying to call DB2 Stored procedure from entity framework. I have created Store schema and conceptual schema based on the SP. I have specified an Entity as a return type to get the data back from SP call. At design time, i am getting the below message as warning
Warning 1 Error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer DB2Container12345.
At runtime I am getting the below error..
Runtime Error :
Schema specified is not valid. Errors:
Data.DB2.msl(6,6) : error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer DB2Container12345.
Any help would be appreciated. I am almost stuck up with this point...
Thanks,
Ganesan Subbian