Model is not reading from my Database (Entitity Framework) - entity-framework

I created simple MVC application with a database.
First I created a database, initialized the database, then I created a model from the database and the application worked..
Then I decide to load database with totaly different values (but the definitons of tables/fields stayed the same)..
After reloading the database my application does not shows any data from my DB. Using debugger I saw that my application cannot get any data from the table.
Worse - I noticed that additional to my database TestDB, the database explorer is showing TestDB.mdf1 database, with the same definitions as testDB.mdf but table is empty...
Here is the code:
public ActionResult ShowQuestions()
{
TestDBEntities _db = new TestDBEntities(); // this is the database
ObjectSet<question> all_quest = _db.questions ; // this is the table
foreach (var x in all_quest)
{
..... // this part was never executed
}
return View(q_list);
}
Any ideas what I am doing wrong?

1- check the connection string in your MVC application (web.config). This will tell you which database is being used. Then go to this database and check if you have data in your tables.
If it's the wrong database, just amend the connection string.
2- If it's the correct database, but without data, just add data.
It may have been recreated by your ORM (who knows?).
3- What is the error you are getting? Or are you getting any error?

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;"

Retrieving some columns from database with Breeze.js, and still be able to update database

I am new to Breeze.js, but really enjoy it so far. I ran into an issue with updating a database with Breeze.js, when selecting only portion of columns of a model.
When I ran this statement:
$scope.emFac.entityQuery.from('Company');
the company entity matches my EF entity, retrieves all columns, creates entityAspect, and all is working fine when updating database:
However, when I retrieve only portion of corresponding Model's columns, Breeze.js returns anonymous object with specified properties (retrieving data works, but not updating does not), without the entityAspect, which is being used for tracking changes.
Here is the code with select statement:
$scope.emFac.entityQuery.from('Company').select('companyId, displayName');
Is there a way to retrieve only some columns of EF Model columns, and still track changes with Breeze.js, needed for database updates?
As you've discovered, Breeze treats the incoming data as plain objects instead of entities when you use select.
Your choices are:
On the server, Create a CustomerLite or similar object, and have a server endpoint that returns those without the need for select; OR
On the client, get the results from the query and create entities from each object, with status Unchanged
Example of #2:
var entities = [];
em.executeQuery(customerProjectionQuery).then(queryResult => {
queryResult.results.forEach(obj => {
// obj contains values to initialize entity
var entity = em.createEntity(Customer.prototype.entityType, obj, EntityState.Unchanged);
entities.push(entity);
});
})
Either way, you will need to ensure that your saveChanges endpoint on the server can handle saving the truncated Customer objects without wiping out the other fields.

How to use EF core owned entites

I am using a SQLite database EFCore 2.0 preview in UWP Project.
The address table is split into to different entities
Delivery address,
Invoice Address
using
modelBuilder.Entity<Project>().OwnsOne(p => p.DeliveryAddress);
which works great for setting up the database, with migrations, creates the different table in the database. With test data that I have put in manually works great at reading data from these tables. But how do I save changes to the DeliveryAddress table. Nothing is getting persisted to the database, when I save the using:
public void UpdateDeliveryAddress(Project modifiedProject)
{
using (var db = new SteelFrameCalculatorDataContext())
{
db.Entry(modifiedProject).State = EntityState.Modified;
db.SaveChanges();
}
}
Project being the parent entity
2017-06-11T23:21:10.9242463+01:00 Warning 8 Microsoft.EntityFrameworkCore.Model.Validation
The key {'ProjectId'} on entity type 'Project.DeliveryAddress->Address' contains properties in shadow state - {'ProjectId'}. To configure this warning use the DbContextOptionsBuilder.ConfigureWarnings API (event id 'CoreEventId.ModelValidationShadowKeyWarning'). ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.
Using the following allowed in to save updates to the database. Assume the UpdateRange(entity) sets all to modified. Not sure if this is the correct way, but it works.
using (var db = new SteelFrameCalculatorDataContext())
{
db.UpdateRange(modifiedProject);
db.SaveChanges();
}
Have you tried setting the state of the child object? Looks like you're only setting the parent Project state.
Adding this should do it:
db.Entry(modifiedProject.DeliveryAddress).State = EntityState.Modified;
db.Entry(modifiedProject).Reference(a=>a.DeliveryAddress).TargetEntry.State = EntityState.Modified;

Dis-Advantages of using EF 6.x.x Code First without Migration

I am fed up of using/running Add-Migration and Update-Database because lot of time we forget to run migrations on production database. So, we decided to delete all migrations from database table as well all migration classes. So, what if my __MigrationHistory table remains always empty and no migration classes. What is the main disadvantage?
No this is a bad idea, the [__MigrationHistory] is used to compare your current used conceptual model with the storage model.
1) Case: DbMigrationsConfiguration automatic:
[__MigrationHistory] keeps track for the last migration.
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
as shown in the image above, the migrationId is the migration identifier and the model column is a base64 representation of the binary stream of your current conceptual model.
2) Case: DbMigrationsConfiguration non-automatic:
[__MigrationHistory] keeps track of every migration.
this.AutomaticMigrationsEnabled = false;
this.AutomaticMigrationDataLossAllowed = false;
Each migration level obtain a migrationId identifier which is used for migration level up/level/down.
Best practice: If you want to use the automatic migration just regenerate the migration and shipped to the custmer.
If you are using non-automatic migration.
1) If the customer need the data then just tranform the data with SQL to the new db schema
2) If the customer does not need the data then just drop the database an create it again with initialCreate.
If you want to create the database without any migrationHistory info:
// Create the database. You can generate it from SMO "Script database as" and if the database exist then just ignore the creation
// Do not forget to remove the [__MigrationHistory] rows.
DbContext.Database.ExecuteSqlCommand("SQLCreateDbScript.sql");
Database.SetInitializer<MyDbContext>(null);
using (var dbContext = new MyDbContext())
{
// Create DbContext and it works!
dbContext.Users.Add(new User());
dbContext.SaveChanges();
}
I hope this will help you to solve the problem!
And if you want something really with less Db-Schema then use NoSql with EF.
In Core version still not done but with the old version EF6 it is possible todo that (NoSql Db) with: http://www.brightstardb.com or use the Polyglot appoarch from microsoft https://msdn.microsoft.com/en-us/library/dn271399.aspx

EF code first - Model compatibility cannot be checked because the database does not contain model metadata

I have enabled automatic migrations. Then, I deleted my whole db. Next, i executed Update-database from command console, and it recreated my db. Then, I started my application only to see this error:
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.
So what exactly is that metadata, and how can I point entity framework to it?
PS. My database contains table named MigrationsHistory.
Here is a detailed description of the possible ways to resolve this which I wrote a while ago...
(not exactly what you're experiencing, hence not a duplicate per se, but with different scenarios in mind)
https://stackoverflow.com/a/10255051/417747
To summarize...
What works for me is to use Update-Database -Script
That creates a script with a 'migration difference', which you can
manually apply as an SQL script on the target server database (and you
should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...
a) remove the migration table (target - under system tables) - as per
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx
comments in there - that should fail back to previous behavior and if
you're certain that your Db-s are the same - it's just going to 'trust
you',
b) as a last resort I used - make a Update-Database -Script of the
full schema (e.g. by initializing an empty db which should force a
'full script'), find the INSERT INTO [__MigrationHistory] records,
just run those, insert them into the database, and make sure that your
databases - and code match,
that should make things run in sync again.
if it helps
Detach your local Database say example 'database1.mdf' from visual studio 'server explorer' and then open SQL server management studio right click on Databases > Attach and then browse the same 'database1.mdf' file .If you doesn't have access then copy&past both the mdf and ldf files into c drive and do attach.
Then open new query window on sql server then do copy your identity tables as like below query.
*'select * into [__MigrationHistory] from Database1.dbo.__MigrationHistory '*
Add this to your context:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
I use Entity Framework 6 , SQL 2008 R2 , VS 2013.
To solve this problem only use the following procedure :
1) delete existing db ( existing database that created with EF model{code first})
2) Run APP again.
Fore example query code (in Layout):
this code create db if my model is change and search username in user table.
<body>
#{
// Delete && Create ...
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DBContext>());
var db = new DBContext();
var SearchingUser = db.Users.Where(c => c.UserName == "qwertyui");
if (SearchingUser.Count() == 0) {
var User = new Users { UserName = "qwertyui",Password = "12345678" };
db.Users.Add(User);
db.SaveChanges();
}
}
#RenderSection("scripts", required: false)
#RenderBody()
</body>
Package Manager Console > Enable-Migrations -EnableAutomaticMigrations
Configure Migrations/Configuration.cs
Package Manager Console > Update-Database