How to clear Validation Results in an Entity Framework Object - entity-framework

It is possible to clear the Validation Results in an ObjectContext associated with an Entity Framework? What I wanted is something like this code:
public void ClearValidationResults (ObjectContext db)
{
var dbContext = new DbContext(db, true);
var validationResults = dbContext.GetValidationErrors();
validationResults.Clear();
}
I want to implement this functionality to use in unit tests to test the validation rules without to have to save changes in DataBase.
Thanks.

DbContext does not store validation errors, it validates entities each time you call DbContext.GetValidationErrors() or DbContext.SaveChanges(). So, if you have an invalid entity that is being tracked by your context DbContext.GetValidationErrors() will always return errors. You need to detach or fix the invalid entity/entities and the error will go away since there will be no invalid entities tracked by your context.

Clear Entity Local Storage.
When we adding Entity to Collection, its adding it to its Local Storage and we kept getting errors as the Local Storage of that Entity is not clear and still having old entries. So you Clear Entity Local rows.
dbContext.EntityName.Local.Clear();

I resolve the problem by creating a new ObjectContext object every time I need to clear the validation errors. Is not the most elegant solution but it works. Since this process is in the context of unit tests and the unit tests are fast enough, I will maintain this code until best solution arrived.
public void ClearValidationResults (ObjectContext db)
{
db = new MyObjectContext();
}

Related

entity framework error there is already an object with that name available in the database

I am using the Entity Framework POCOs to assist with migrating data from a legacy database to a new database. Both databases already exist and the Entity Framework has no part in creating or modifying structure for either. I created a sample database on the migration server and restored it to my local computer sql server (entirely in t_sql, no EF) and my context and its data classes are working fine and returning the data I want. Today I went to the production migration server and when I go to run my first test I get the above referenced error.
All I am doing is reading data, no writing, so this makes no sense to me. EF must be doing something when it hooks up the data context that I can't see. The error is coming from SqlClient.SqlConnection. There is no inner exception, no help link and nothing in the call stack except my method
Any ideas where to start looking?
Pamela
So it turns out the Entity Framework gets mad when the database changes at any point. You need to tell it to ignore the database. I did it by creating this base class for my data contexts
enter code here public class BaseContext<TContext> : DbContext where TContext : DbContext
{
protected BaseContext()
: base("Foxpert.HS.ChangeDetection.VHSContext")
{
Database.SetInitializer<TContext>(null);
Configuration.AutoDetectChangesEnabled = false;
}
}

Having static Repository class in a webforms project reuses entity framework connections?

I have a
public static class Repository
in my webforms project.
In the static block of that class I setup my entity framework entity object:
private static readonly ProjectEntities db;
static Repository()
{
db = new ProjectEntities("Name=ProjectEntities");
}
Then I setup some public static methods like this:
public static Order GetOrder(int orderID)
{
return db.Orders.First(o => o.OrderID == orderID);
}
The problem is that when for instance deletions fails (because of some constraint), I randomly gets some clues about that in subsequent connections, coming up as exceptions as a result of queries that should be innocent. For instance, exceptions about deletions as a result of select queries.
I never
db.AcceptAllChanges();
upon any exception, and I should not have to, because across page accesses, there should be no trace of failed queries. Or should it? Is the cleaning responsibility on me?
Those problems should not be because of me using static (please say it is not like that), so is it related to entity framework connection pooling?
Generally speaking the entity framework context is meant to be short lived - i.e. it is generally regarded as a unit of work whereby you create it for a particular task and dispose of it at the end. It's a light weight object, and should be used in this way.
You issue is as a result of the object being long lived (i.e. in a singleton shared across requests). In this case the internal state of the context is becoming invalid - i.e. you try to delete something, it cannot persist those changes to the database, and is therefore in an invalid state.
You could probably resolve your issue by calling the refresh method before making use of the object in every case - this will cause the object to update its state based on the database - but this will probably cause other issues.
However, this is the wrong thing to do - the context should be created, used and disposed per request.
Hope this helps.
I would seriously suggest you investigate the lifecycle management of your context object.
Have a look at this excellent answer as to what your options are.

Best way to incrementally seed data in Entity Framework 4.3

I have been using Entity Framework 4.3 on an existing database and I have a couple of scenarios that I am trying to cater for.
Firstly, if I delete my database I would like to EF to recreate if from scratch - I have successfully used a CreateDatabaseIfNotExists database initialiser for this.
Secondly, if I update my model and the database already exists I would like the database to be updated automatically - I have successfully used Entity Framework 4.3 Migrations for this.
So here's my question. Say I add a new table to my model which requires some reference data, what it the best way to ensure that this data gets created both when the database intialiser runs and also when the migration runs. My desire is that the data gets created when I'm creating the db from scratch and also when the database gets updated as the result of a migration running.
In some EF migrations examples I have seen people use the SQL() function in the UP method of the migration to create seed data but if possible I would rather use the context to create the seed data (as you see in most database initialiser examples) as it seems strange to me that you would use pure sql when the whole idea of EF is abstracting that away. I have tried to use the context in the UP method but for some reason it didn't think that a table that was created in the migration existed when I tried to add the seed data directly below the call to create the table.
Any wisdom greatly appreciated.
If you want to use entities to seed data you should use Seed method in your migrations configuration. If you generate fresh project Enable-Migrations you will get this configuration class:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CFMigrationsWithNoMagic.BlogContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
The way how migrations seed data are not very efficient because it is supposed to be used for some very basic seeding. Every update to new version will go through whole set and try to update existing data or insert new data. If you don't use AddOrUpdate extension method you must manually ensure that data are seeded to database only if they are not present yet.
If you want efficient way for seeding because you must seed o lot of data you will get better result with common:
public partial class SomeMigration : DbMigration
{
public override void Up()
{
...
Sql("UPDATE ...");
Sql("INSERT ...");
}
public override void Down()
{
...
}
}
I wouldn't recommend using Sql() calls in your Up() method because (IMO) this is really intended for actual migration code for which there is no built-in function, rather than seed code.
I like to think of seed data as something that could change in the future (even if my schema does not), so I simply write "defensive" checks around all of my inserts in the seed function to make sure that the operation did not fire previously.
Consider a scenario where you have a "Types" table that starts out with 3 entries, but then you later add a 4th. You shouldn't need a "migration" to address this.
Using Seed() also gives you a full context to work with, which is a lot nicer than using the plain sql strings in the Sql() method that Ladislav demonstrated.
Also, keep in mind that the benefit of using built-in EF methods for both the migration code and seed code is that your database operations remain platform-neutral. This means your schema changes and queries are be able to run on Oracle, Postgre, etc. If you write actual raw SQL then you are potentially locking yourself in unnecessarily.
You might be less concerned about this since 90% of people using EF will only ever hit SQL Server, but I'm just throwing it out there to give you a different perspective on the solution.

How to get freshly added entities from repository?

I'm using a repository implementation which is using a shared ObjectContext with other repositories. The repository holds an ObjectSet of the entities. I'm adding new entities via Add() method to the ObjectSet. While importing data I would like to query those fresh added objects to prevent duplicate data.
The ObjectContext implements a unit of work pattern. At the end of the import process I would like to call the commit method which calls context.SaveChange() to persist the data.
However, I couldn't find an easy way to query the freshly added entities before I called SaveChanges(). How do you guys handle such problems?
Query the ObjectStateManager.
var foo = context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added)
.Select(s => s.Entity).OfType<Foo>().SingleOrDefault(f => f.Id == bar);
I used ObservableCollection inside repository.cs to get the data before saving it to database as below
public ObservableCollection<T> Local {
get { return UnitOfWork.GetContext().Set<T>().Local; }
}
if you want you can also use ICollection because it is a base class for observablecollection.
Now, you can query the repository as shown below...
Repository.Local.Where(x=>x.TrackingNumber == order.TrackingNumber).SingleOrDefault();
But, remember you cannot get data using Id's before saving to database so use some other unique field to get data. For further info click on the below link where similar kind of question was asked by me
Why I am not able to get recently added objects (yet to be saved in database) from repository

How to create a static UnitOfWork for entity framework 4?

Considering this class
public class XQueries
{
public IQueryable Query1()
{
using (XEntities context = new XEntities())
{
return something;
}
}
public IQueryable Query2()
{
using (XEntities context = new XEntities())
{
return somethingElse;
}
}
}
Is a connection to the database created for every (XEntities context = new XEntities()) {...} ? If so what is the correct way to create a static UnitOfWork class so that only 1 connection to exist?
You can't create a static unit of work, because by definition a unit of work is a short lived object. Because the EF ObjectContext is designed around the unit of work pattern it is a bad idea to have a single ObjectContext instance during the life time of the application. There are several reasons for this.
First of all, the ObjectContext class is not thread-safe. This means that during the unit of work of one user (in a web app for instance), another user can commit his unit of work. When they share the same ObjectContext, it means that in that situation just half of the changes are persisted and changes are not transactional. When you are lucky the ObjectContext fails and throws an exception. When you are unlucky, you corrupt the ObjectContext and safe and load crap from and to your database and find out when your application is running in production (of course, during testing and staging everything always seems to work).
Second, the ObjectContext has a caching mechanism that is designed for it to be short lived. When an entity is retrieved from the database it stays in the ObjectContext’s cache until that instance is garbage collected. When you keep that instance alive for a long period of time, entities get stale. Especially if that particular ObjectContext instance is not the only one writing to that database.
The Entity Framework opens connections only when required, for example to execute a query or to call SaveChanges, and then closes the connection when the operation is complete.
From Martin Fowler’s book Patterns of Enterprise Application Architecture in respect to Unit Of Work.
When you're pulling data in and out of
a database, it's important to keep
track of what you've changed;
otherwise, that data won't be written
back into the database. Similarly you
have to insert new objects you create
and remove any objects you delete.
You can change the database with each
change to your object model, but this
can lead to lots of very small
database calls, which ends up being
very slow. Furthermore it requires you
to have a transaction open for the
whole interaction, which is
impractical if you have a business
transaction that spans multiple
requests. The situation is even worse
if you need to keep track of the
objects you've read so you can avoid
inconsistent reads.
A Unit of Work keeps track of
everything you do during a business
transaction that can affect the
database. When you're done, it figures
out everything that needs to be done
to alter the database as a result of
your work.
Whenever I use Entity Framework for a clients (which I'd admit is rare) the ObjectContext object is the Unit Of Work implementation for the system. That is the ObjectContext will somewhat meet the three statements above. Rather than concentrating too much on the absolutely correct definition using the ObjectContext makes things a little easier for you.
Do some research on DI/IoC and Repository patterns this will give you more flexibility in handling your problem.