Calling DB2 stored procedure from Entity Framework - 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

Related

Datareader is incompatible with the specified 'result set complex type'. A member of the type

I have a stored procedure that updates a date column in a table in MS SQL Server database. This stored procedure does not have any complex logic. It does a simple update on the date column with the value passed in its input parameter. This stored procedure does not return any result set upon successful execution but returns a result set with a few columns with names ErrorNumber, ErrorSeverity etc., when the stored procedure execution throws an exception from the try..catch exception handling block.
I am using DB First entity approach; I have updated Entity Data Model for this stored procedure from my asp.net MVC web application. Entity framework designer generated a complex type for the return type on this stored procedure with a property for each of the columns in the columns list returned in the catch block. When I invoked the stored procedure from asp.net MVC application with valid input parameters, I encountered the "Datareader is incompatible exception". I know this exception is triggered by entity framework because the stored procedure execution does not return a result set and the framework is expecting a column to be returned back with the name "ErrorNumber". I invoked the stored procedure directly with the db context instance with required valid parameter values.
for example db.UpdateProcedure(dueDate). I did not use a data table to load the data from the data reader. I know loading the result set into a data table will not cause this exception.
After making a minor change to the stored procedure to return ##rowcount on successful execution, the application did not throw this exception upon this stored procedure invocation.
I am wondering if there is a better way to deal with this situation without updating the stored procedure to return ##rowcount.
I am using the designer generated entity model from the database; I did not make any manual changes to the schema after auto-generation of the entity model. To be honest, I don't like doing manual changes to the schema once it is auto-generated.
Is there anything I am missing during the entity schema update for this stored procedure to have correct complex type generated when the model is updated from entity designer?
Is the stored procedure returning a result set upon exception occurrence and not returning any result upon successful execution causing any problem to the process that updates entity schema?
Your help is much appreciated.
Thank you in advance.

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

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.

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!

EF retrieve entities from undefined table/view

Is it possible to retrieve records from a view that has not been defined in the model and to retrieve his columns value by using column name or ordinal ?
I write this code :
AppContext ctx = new AppContext("name=DbConnString");
string commandText = "SELECT V.ID, V.Code, V.Description FROM vw_UserDefinedView AS V";
ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(commandText, ctx);
but an exception occurred when I try to execute it :
'vw_UserDefinedView' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near simple identifier, line 1, column 43.
Is there a way to accomplish this using Entity Framework and ObjectContext (or DbContext) ?
Best regards,
Alberto
No, this is not possible. As the message already states: "'vw_UserDefinedView' could not be resolved in the current scope or context." This view is not known to the context (.edmx). You have to realize that you are querying the Entity Model and not the Database!
If you don't want this view (for whatever reason) in your Entity Model, then simply use SqlCommand, SqlConnection and SqlDataReader to execute your statements concerning vw_UserDefinedView.
UPDATE
Maybe this link can help you further: Entity Framework : Add Properties/Entities during runtime

Entity Framework - Mapping decimal(13,0) problem

I'm migrating the aplication of my company (that nowadays run over SQL Server and Oracle) to ASP NET MVC and Entity Framework for persistence.
A create my Entity Model based on SQL Server Database e separately I create a SSDL for Oracle (for Oracle I use DevArt dotConnect for Oracle Provider) and I get some pain troubles.
My table primary keys are on SQL Server are of type decimal(13,0) and on Oracle are number(13,0) but Oracle map it's type to Int64 and SQL Server to decimal, but I need that SQL Server map it to Int64.
I make these modification manually on Entity Data Model and for create records it's works fine, but when I have to delete or update some record I got these error:
The specified value is not an instance of type 'Edm.Decimal'
Parameter name: value
at System.Data.Common.CommandTrees.DbConstantExpression..ctor(DbCommandTree commandTree, Object value, TypeUsage constantType)
at System.Data.Mapping.Update.Internal.UpdateCompiler.GenerateValueExpression(DbCommandTree commandTree, EdmProperty property, PropagatorResult value)
at System.Data.Mapping.Update.Internal.UpdateCompiler.GenerateEqualityExpression(DbModificationCommandTree commandTree, EdmProperty property, PropagatorResult value)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildPredicate(DbModificationCommandTree commandTree, PropagatorResult referenceRow, PropagatorResult current, TableChangeProcessor processor, Boolean& rowMustBeTouched)
at System.Data.Mapping.Update.Internal.UpdateCompiler.BuildDeleteCommand(PropagatorResult oldRow, TableChangeProcessor processor)
at System.Data.Mapping.Update.Internal.TableChangeProcessor.CompileCommands(ChangeNode changeNode, UpdateCompiler compiler)
Someone can help me?
Why Entity Framework mapping are so fixed? It could be more flexible?
Ps.: The error that I got, I suspect that is because of a association.
I have a Entity named Province and another named Country and I think that the association between these Entities are causing the problem at update and delete.
Regards,
Douglas Aguiar
This may or may not help you, but i had the same error from doing this same thing. So I edited the Conceptual model and change the primary key field from Int32 to Decimal. So far, seems to have fixed things. I still need to test again against Sql Server and make sure this didnt break it.
I was getting the error "The specified value is not an instance of type 'Edm.Decimal' Parameter name: value" as you posted in your question. I had changed the default data types from Decimal to Int32 as this better reflects the true typing. When I first hit this error I rolled back the type changes and was still getting an exception but it changed just slightly but led to further digging. Bottom line, in my scenario we were expecting a trigger to populate the PK during persistence via Before Insert directive. The problem was that the domain class built by EF was setting the PK at 0 so the trigger was never firing as the incoming PK was not null. Of course EF will not let you set the Entity PK to be nullable. Maybe this will help someone else in the future.