Why doesn't my application see Entity Framework model updates - asp.net-mvc

I have an MVC application that uses Entity Framework. I needed to create a new stored procedure for the application to use. I created the stored procedure in the database first so I know it exists. Then in my project, I updated the model from the database and pulled in the new stored procedure. Then I created a function import with a complex type and saved the model. I have a service that is using the model and I can reference the new complex type without a problem.
The issue I run into is when running the application and hitting this stored procedure, I get an error that says "Could not find stored procedure."
The method throwing the error is here:
public virtual ObjectResult<E3_Assessment_GetPDFImages_Result> E3_Assessment_GetPDFImages(Nullable<int> assessmentID)
{
var assessmentIDParameter = assessmentID.HasValue ?
new ObjectParameter("assessmentID", assessmentID) :
new ObjectParameter("assessmentID", typeof(int));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<E3_Assessment_GetPDFImages_Result>("E3_Assessment_GetPDFImages", assessmentIDParameter);
}
Are there any additional steps I need to take to make sure the everything is updated in the Entity Framework? I have verified the stored procedure exists in the database. The only other thing I can think of is that the model is not seeing the new stored procedure.
UPDATE Connection String
<add name="AssessmentEntities" connectionString="metadata=res://*/AssessmentModel.csdl|res://*/AssessmentModel.ssdl|res://*/AssessmentModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MyServer;initial catalog=MyDatabase;persist security info=True;user id=MyUser;password=MyPassowrd;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
UPDATE
I ran sql server profiler and found why I'm getting the error. When the stored procedure runs it is running in the master database instead of the actual database it should run in. Other stored procs are running in the correct database.
Why is it running in the master database instead of the database I want?

I had to reinitialize my context before calling the stored procedure. That is why it was using the master database.

Related

Entity Framework and Membership Provider not working

I had an application which used the Asp.net Membership provider. I converted this project to EF4 and trying to use the same authentication.
I am using the old DB for my connection as
<add name="Entities1"
connectionString="metadata=res://*/DbContext.csdl|res://*/DbContext.ssdl|res://*/DbContext.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Master.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
<add name="PondsMasterEntities"
connectionString="metadata=res://*/DbContext.csdl|res://*/DbContext.ssdl|res://*/DbContext.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\PondsMaster.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
And now I am ending with this 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: 50 - Local Database Runtime error occurred. The specified LocalDB instance does not exist
on
var result = await UserManager.CreateAsync(user, model.Password);
But when I use like this. I can add delete entries from the DB.
private Entities1 db = new Entities1();
db.IssueMasterLogs.Add(log);
Any thoughts?
Looks like you're using a database first approach and an existing database for a project that uses ASP.Net Identity. By default, Identity (V2) works with a code first approach, creating it's required tables in the database. Usually, people end up having a separate connection string for Identity because of this (even though both connection strings point to the same database).
In your case, simply switching the DefaultConnection Identity uses to your connection Entities1 will not help since it is not code first. You can however, keep the DefaultConnection and modify it to point to your db, and keep using it code first. If you do this, you will have two connection strings (Entities1 and DefaultConnection) that both point to the same database and are database first and code first, respectively.
For a db first a approach with Identity, you might want to take a look at this.

How can I get the current connection

Given Scenratio:
We've built a web application using Asp.net MVC and Entity Framework Code First, which builds a database dynamically for each customer.
Given a connection string (connectionStr) and a certain Configuration, We've made Add Migrations [Name] in order to create an empty migration, which has an empty Up function. We did that on purpose.
We don't wanna use automatic migrations here - we want full control, so we have a program making the migrations using a DbMigrator Class.
Our goal is to run a manual Seed inside this Up function.
This is some of the code incharge of making the migration, which indeed works perfectly:
Dim myConfiguration As New SomeNamespace.Migrations.Config1.Configuration
myConfiguration.TargetDatabase = New Infrastructure.DbConnectionInfo(connectionStr, "System.Data.SqlClient")
Dim dbMig As New Entity.Migrations.DbMigrator(myConfiguration)
If dbMig.GetPendingMigrations.Count > 0 Then
dbMig.Update() ' This makes the Up function work - the problem is inside it.
End If
Problem:
The problem is that when the Up function of the Migration is run, we cannot get the database context. We need it in order to make a Seed.
We hope that there's a way to get the Configuration object (myConfiguration) used to initiate the DbMigration (dbMig) instance, or some other way, so we can get the database context (maybe getting the ConnectionString somehow).
Help getting access to one of configuration object / database context / ConnectionString - would be very appreciated.
I don't think so, because what Up method does is filling Operations collection, and DbMigrator class actually executes these operations. So there is no 'context' when up is called.
What you can do is get connection string via ConfigurationManager class directly

The model backing the 'DMSContext' context has changed

I'm receiving the following error when running my mvc 4 app.
The model backing the 'DMSContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I am running my app against an existing database and do no want to recreate the db each time the model changes.
I've found plenty of answers on google, but none have worked.
Specifically, I've tried adding the following to my global.asax:
Database.SetInitializer<DMSContext>(null);
and
Database.SetInitializer<DMSContext<Contact>>(null);
in the above, DMSContext is the DbContext. Contact is the Model where the change causing the error originates.
I've also tried adding the following to my context class:
public DMSContext() : base()
{
Configuration.AutoDetectChangesEnabled = false;
}
Most of the direction I've followed is from this page, but no luck.
The model backing the <Database> context has changed since the database was created
If you are working with Entity Framework Code First, its recommended that you enable migrations in your application. To do so, see this link.
Now every time you change something in your code (Mostly Entities), just build and then run Update-Database -Force in your Package Manager Console.
Let me know if you have any more questions.
Although you don't use migrations try to create one, do not run it, but you'll be able to see the differences with the database.
Check the name of the class, which inherits the DbContext. It's name have to be the same as the name of the connectionString in Web.config
<connectionStrings>
<add name="TheSameNameAsYourDbContextClass" providerName="" connectionString="" />
</connectionStrings>

Understanding VS's ability to create database on first run

I'm working with a (.net4 / mvc3 ) solution file downloaded (from a reputable source) where a connection string exists in web.config but I don't see explicit instructions to create the database and there's no included '.mdf'. The first time I build I got a runtime error regarding lack of permissions to CREATE database. So I created a blank db and made sure the string referenced a SQL user that had .dbo/owner rights to the db just created.
But subsequent builds don't seem to execute that same initialize db script - where ever that's stored.
Where is this 'first use' convention for creating databases documented?
thx
That is a feature of Entity Framework Code First. I am not sure what you are looking for exactly, but searching for "EF Code First Initialization Strategy" might help.
For instance read this article: EF Code First DB Initialization Using Web.Config
I assume you are talking about Entity Framework, which allows you to create the database from an instance of an ObjectContext object, which is used in any of the three approaches in EF (database-, model- and code-first).
Look for a line that actually calls ObjectContext.CreateDatabase(). If one of the supported ADO.NET provides is used (SQL Server or SQL Server CE 4.0) this will generate the required SQL Statements. Assuming the classic Northwind example, you might find something like that:
NorthwindContext context = new NorthwindContext();
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
If this is in fact a code-first application, "lalibi" is right about the initialization strategy which by default doesn't require you to explicitly create the database. (But my guess is, that it actually uses a statement internally very similar to mine).

Entity Framework 4 and DB2: database generation error

We are using Entity Framework 4 RC on Visual Studio 2010 with DB2 version 9.7.3.4. I also have the VS Add-ins and can see the DB2 database in Server Explorer. I have created a very simple VS console project and it works fine against SQL Server, so I know it is valid. I have references to "IBM.Data.DB2.9.7.3" and "IBM.Data.DB2.Entity" in my project.
In app.config my connnection string is:
<add name="ProductContext"
providerName="IBM.Data.DB2"
connectionString="Database=DB2TEST;User ID=XXXX;PWD=XXXX;Server=XXXX;Persist Security Info=True;"/>
The first statement in my code is a database initializer:
DbDatabase.SetInitializer<ProductContext>(new DropCreateDatabaseIfModelChanges<ProductContext>());
During run-time when I reach a line that causes a change to the data context I get the error:
Model compatibility cannot be checked
because the database does not contain
model metadata.
Since I requested that the database be dropped, this does not seem to be a logical error. Does anyone know what the cause could be?
I would try to inherit from CreateDatabaseIfNotExists first, which will add the EdmMetadata table to the schema. I believe the error is that EF is saying that it cannot find that table.
So
DbDatabase.SetInitializer<ProductContext>(new CreateDatabaseIfNotExists<ProductContext>());
Run it once, then change to DropCreateDatabaseIfModelChanges once the EdmMetadata table exists.
Try removing the IncludeMetadataConvention like this:modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();
To avoid the "dbo" issue, just map all your entities using either DataAnnotation attributes or Fluent mapping:
[Table("Product", SchemaName = "MySchema")]
public class Category { //DataAnnotoaion approach
modelBuilder.Entity<Category>().ToTable("Categories", "MySchema"); //Fluent approach

Resources