I am using SQL Server R2 for my Database. Now I am getting this kind of error frequently :
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.
InnerException: {"Invalid column name 'someColumn'."}
Here in the model every thing is fine and in database also. I know this is due to cache in dbcontext. I want to clear and rebind the dbcontext every time when I run the project. I googled for the solution and I got this solution, but I am unable to do the desired operation after declaring like this.
public class EFDbContext: DbContext
{
public DbSet < utblCategoryMaster > utblCategoryMasters { get; set; }
public DbSet < utblsubCategoryMaster > utblSubCategoryMasters { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
I am new to MVC and I don't know how to refresh entity framework. Is there any solution?
Entity framework model caching is done only at the AppDomain level, so if you build you project, restart IIS or recycle the application pool the caching will be gone.
To quote from the link you shared:
The model for that context is then cached and is for all further instances of the context in the app domain.
I think the problem is , there is mismatch between the schema and the mapping file. Can you double check the database, connection string and schema/mapping files?
Some additional information can be gained by running SQL Profile, as it can show you the exact query that is being executed when the error happens. But you will need to configure the profiler to show the errors.
Related
My Database Team created a database called XMEN.
I need to use that specific database with my project. I have full admin rights on that database but not on the server (they won't give it to me).
CREATE DATABASE permission denied in database 'master'.
When I run my project, I get the error above because I don't have permission to create a database. How can I use entity frameworks to specify which database to use? I want Entity Framework to manage everything else (tables, relationships, etc)
------------- UPDATED 9/17/2020 - 9:12 AM EST
public class XmenContext : DbContext
{
//public XmenContext(DbContextOptions<XmenContext> options)
// : base(options)
//{
//}
public XmenContext() : base("XmenDatabase")
{
}
Now I get an error saying cannot convert from String to Microsoft.EntityFrameworkCore.DbContextOptions
I clicked the link in your answer.
You should add the database name to the connection string in your configuration file.
If you need some help you can view here :
https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/connection-strings
If you are having trouble add your connection string to the question (without sensitive information) and I will try to help.
Good luck !
I have a SQL Server CE database configured with Entity Framework code-first with a model class InfoLog as follows:
public class InfoLog
{
[Key]
public int Id { get; set; }
public string Item { get; set; }
}
And I save list of logs to this table using,
conn.InfoLog.AddRange(items.Select(x => new InfoLog { Item = JsonConvert.SerializeObject(x) }));
And after certain time I sync those logs with server and flush it from database using,
conObj.InfoLog.RemoveRange(itemsToFlush);
Now usually (For months for hundreds of users) it works perfectly fine, but all of sudden I start getting following error (for some random user),
System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at DataService.SaveInfoLog(List`1 items)
It clearly state to check EntityValidationErrors, but I am unable to replicate that, even with the same SQL Server CE database on which the issue is occurring.
Now with model specified above what kind of EntityValidationError could occur is really tough question for me.
And I am impatient to wait for next time it occurs, can anyone suggest how can I proceed to solve this.
Update:
If we debug with same database, then records get saved.
And on end user machine if we restart application then also records get saved.
I'm writing a web api attached to a database that I created using Model First.
Being new I was confusing Model First with Code First.
As it's my first EF/Web app I didn't realize that migration wasn't yet implemented by Model First and I followed the procedure to implement it. When it ran I received some errors, looked them up and only then realized I'd need to remove it again.
Following somebody's instructions I deleted the migrations folder, plus the _migrationHistory table from the database.
But now I receive the following exception whenever the _migrationhistory table is missing from the database.
protected void Application_Start()
{
// Call initializer
Database.SetInitializer(new PulseDbInitializer());
new ApplicationDbContext().Database.Initialize(true); <- error here
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
"An exception of type 'System.NotSupportedException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations."
The following is a partial description of my initializer
public partial class PulseDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>, IPulseDbInit
//public partial class PulseDbInitializer :DropCreateDatabaseAlways<ApplicationDbContext>, IPulseDbInit
{
private ApplicationDbContext _context;
protected override void Seed(ApplicationDbContext context)
{
_context = context;
var pid = new PulseDbInitializionData(context);
pid.Init(this);
}
}// class PulseDbInitializer
It seems that the app is trying to use migrations (because it's creating the _migrationhistory table) even though I've removed the migrations subfolder.
Being new at this, I'm not sure where to go. I'm aware that I've created my initializer, see above, so am I missing something?
EDIT - Too long for a comment
Im not sure we're understanding each other.
Very simply, I don't know what's generating the _MigrationHistory table in my database as afaik if I remove the Migration subdirectory from my project and delete the database, then I thought that's all I need to do to drop migrations.
In my model first, the DropCreateDatabaseIfModelChanges is what I've always used for generating the database and is working as expected. It creates a new database, or recreates when the model changes.
Until I added the migration I didn't notice this _MigrationHistory table and I don't have a clue if the add-migration command added any code to my project that I need to delete or change (I really hate things happening and not being told exactly what was done in some kind of log. Please microsoft, for future reference)
Or am I totally wrong and the _MigrationHistory table was always there but I never noticed? It all seems to work, as long as I don't remove the table.
Your initializer is inheriting from DropCreateDatabaseIfModelChanges, which checks for model changes. Since you are not using code first you can't check for model changes in code (since your code doesn't define the model -that'd be code-first-... the model defines the code -that's model-first-)... so you need to implement your own IDatabaseInitializer which only checks (for example) that the database exists:
public partial class PulseDbInitializer : IDatabaseInitializer<ApplicationDbContext>, IPulseDbInit
{
public void InitializeDatabase(ApplicationDbContext context)
{
var exists = new DatabaseTableChecker().AnyModelTableExists(context.InternalContext);
if (exists == DatabaseExistenceState.Exists)
{
// maybe check if certain data exists and call the `Seed` method if
// it doesn't
return;
}
// Throw some error if it doesn't exist
}
protected override void Seed(ApplicationDbContext context)
{
_context = context;
var pid = new PulseDbInitializionData(context);
pid.Init(this);
}
}
Following is a part of code in my DbContext that creates data and seeds data.
public class labSchedulerDbContext :DbContext
{
static abDbContext()
{
Database.SetInitializer(new abDatabaseInitializer());
}
public abDbContext() :base (nameOrConnectionString:"abDbContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Rest of the code is just declaring models.
In my setinitializer class with seed
public class abDatabaseInitializer : DropCreateDatabaseIfModelChanges<abDbContext>
{
.....
}
Code is working fine. Problem I have is when I created site in IIS and ran it. It runs fine but after few hours it will delete the database and initialize and seed data again. Thus we lose the data added. I tried to comment out lines where setinitilizer file is being called. Still didn't work. I refreshed apppool and site maybe it was cached files. But still no luck.
Can you please tell me how I can disable the whole initializer file once a database is created so no matter what it doesn't go and drops db and create a new one.
Cod
You can use this other initializer:
CreateDatabaseIfNotExists: This is default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, then it will throw an exception
The only thing that you have to do is to drop the database yourself before you deploy a new version with a different model. (Provided that's what you want to do).
I've added two new properties to my domain model class and two properties to a data table accordingly. Then I tried to launch my mvc web application and got
The model backing the 'EFDbContext' context has changed since the database was created.
Consider using Code First Migrations to update the database
(http://go.microsoft.com/fwlink/?LinkId=238269).
Having read the following posts:
MVC3 and Code First Migrations
EF 4.3 Automatic Migrations Walkthrough
I tried to Update-Database through Package Manager Console, but got an error
Get-Package : Не удается найти параметр, соответствующий имени параметра "ProjectName".
C:\Work\MVC\packages\EntityFramework.5.0.0\tools\EntityFramework.psm1:611 знак:40
+ $package = Get-Package -ProjectName <<<< $project.FullName | ?{ $_.Id -eq 'EntityFramework' }
+ CategoryInfo : InvalidArgument: (:) [Get-Package], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,NuGet.PowerShell.Commands.GetPackageCommand
The EntityFramework package is not installed on project 'Domain'.
But the Entityframework is installed on project Domain. I removed it from references, deleted package.config and sucessfully reinstalled EF. But Update-Database still returns same error. Update-Database -Config does as well
What am I doing wrong?
EDIT
Many thanks to Ladislav Mrnka, I'll try to rephrase my question. As far as I changed my data table manually, I am not expected to use migration. But how can I now make EF work with manually edited domain model class and data table?
Try to add this to startup of your application (you can put it to App_Start):
Database.SetInitializer<EFDbContext>(null);
It should turn off all logic related to handling the database from EF. You will now be fully responsible for keeping your database in sync with your model.
I had the same problem and this is how I fixed the issue.
I dropped table __MigrationHistory using sql command and run the update-database -verbose again.
Apparently something was wrong with this automatic created table.
Answer 2 was exactly what was needed. Although when I got to the App_Start I realized that there were 4 configuration files and didn't see where this would fit in any of them. Instead I added it to my EF database context
namespace JobTrack.Concrete
{
public class EFDbContext : DbContext
{
//Set the entity framework database context to the connection name
//in the Webconfig file for our SQL Server data source QSJTDB1
public EFDbContext() : base("name=EFDbConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Remove the tight dependency on the entity framework that
//wants to take control of the database. EF by nature wants
//to drive the database so that the database changes conform
//to the model changes in the application. This will remove the
//control from the EF and leave the changes to the database admin
//side so that it continues to be in sync with the model.
Database.SetInitializer<EFDbContext>(null);
//Remove the default pluaralization of model names
//This will allow us to work with database table names that are singular
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
//Allows for multiple entries of the class State to be used with
//interface objects such as IQueryTables for the State database table
public DbSet<State> State { get; set; }
}
}