Is it somehow possible to handle concurrency in Entity Framework without adding an additional column like described in this MSDN-article?
There are only solutions described where i have to change the database structure, but it is not possible to change the Database i am working with, so i need another possibility.
EDIT:
The conflicts should be handled optimistic. There are several (hundreds) of tables, so what i am looking for is a more general solution, not specific to one table.
According to this: Handling Concurrency with the Entity Framework
Configure the Entity Framework to include the original values of every
column in the table in the Where clause of Update and Delete commands
If you do want to implement this approach to concurrency, you have to
mark all non-primary-key properties in the entity you want to track
concurrency for by adding the ConcurrencyCheck attribute to them
Related
We are leading into some issues with ef-core on sql databases in a web-api when trying to update complexe objects on the database provided by a client.
A detailed example: When receiving an object "Blog" with 1-n "Posts" from an client and trying to update this existing object on database, should we:
Make sure the primary keys are set and just use
dbContext.Update(blogFromClient)
Load and track the blog while
including the posts from database, then patch the changes from
client onto this object and use SaveChanges()
When using approach (1) we got issues with:
Existing posts for the existing blog on database are not deleted
when the client does not post them any more, needing to manually
figure them out and delete them
Getting tracking issues ("is already been tracked") if
dependencies of the blog (for example an "User" as "Creator") are
already in ChangeTracker
Cannot unit test our business logic without using a real DbContext
while using a repository pattern (tracking errors do just not exist)
While using a real DbContext with InMemoryDatabase for tests cannot rely on things like foreign-key exceptions or computed
columns
when using approach (2):
we can easily manage updated relations and keep an easy track of
the object
lead into performance penalty because of loading the
object which we do not really need
need to map many manual things
as tools like AutoMapper cannot be used to automaticlly map
objects with n-n relations while keeping a correct track by ef core (getting some primary key errors, as some objects are deleted from lists and are added again with the same primary
key, which is not allowed as the primary key cannot be set on insert)
n-n relations can be easily damaged by this as on database
there could be n-n blog to post, while the post in blog does hold
the same relation to its posts. if only one relation is (blog to
post, but not post to blog - which is the same in sql) is posted and
the other part is deleted from list, ef core will track this entry
as "deleted".
in vanilla SQL we would manage this by
deleting all existing relations for the blog to posts
updating the post itself
creating all new relations
in ef core we cannot write such statements like deleting of bulk relations without loading them before and then keeping detailed track on each relation.
Is there any best practice, how to handle an update of complexe objects with deep relations while getting the "new" data from a client?
The correct approach is #2: "Load and track the blog while including the posts from database, then patch the changes from client onto this object and use SaveChanges()".
As to your concerns:
lead into performance penalty because of loading the object which we do not really need
You are incorrect in assuming you don't need this. You do in fact need this because you absolutely shouldn't be posting every single property on every single entity and related entity, including things that should not be be changed like audit props and such. If you don't post every property, then you will end up nulling stuff out when you save. As such, the only correct path is to always load the full dataset from the database and then modify that via what was posted. Doing it any other way will cause problems and is totally and completely 100% wrong.
need to map many manual things as tools like AutoMapper cannot be used to automaticlly map objects with n-n relations while keeping a correct track by ef core
What you're describing here is a limitation of any automatic mapping. In order to map entity to entity in collections, the tool would have to somehow know what identifies each entity uniquely. That's usually going to be a PK, of course, but AutoMapper doesn't (and shouldn't) make assumptions about that. Instead, the default and naive behavior is to simply replace the collection on the destination with the collection on the source. To EF, though, that looks like you're deleting everything in the collection and then adding new items to the collection, which is the source of your issue.
There's two paths forward. First, you can simply ignore the collection props on the source, and then manually map these. You can still use AutoMapper for the mapping, but you'd simply need to iterate over each item in the collection individually matching it with the appropriate item that should map to it, based on your knowledge of what identifies the entity (i.e. the part AutoMapper doesn't know).
Second, there's actually an additional library for AutoMapper to make this easier: AutoMapper.Collection. The entire point of this library is to provide the ability to tell AutoMapper how to identify your entities, so that it can then map collections correctly. If you utilize this library and add the additional necessary configuration, then you can map your entities as normal without worrying about collections getting messed up.
I want to activate Delete Cascade in some relations of my entities, but I don't want to change the database. I wonder if there is a way to do this in Entity Framework.
I mean, it would be perfect if EF just generates automatically the SQL calls to remove all the related records when the parent is removed.
I was trying to add this to my SonEntityTypeConfiguration class:
public SonEntityTypeConfiguration()
{
HasRequired(e => e.Parent)
.WithMany()
.WillCascadeOnDelete(true);
//(...)
}
but I'm getting this error:
The model backing the 'AuditoriaUnitOfWork' context has changed since
the database was created. Consider using Code First Migrations to
update the database
So it seems to be still trying to change the database.
Is there any way to achieve this or I should give up and just ask my database manager to change it?
WillCascadeOnDelete relies on cascading deletes at the database level. So it will require a schema change.
The reason cascading deletes are not implemented at the EF layer is because there are no guarantees that EF will even be used. There are numerous ways to access the database but it is the database's responsibility to ensure that referential integrity is maintained. It cannot rely on higher layers for this.
You have two options here: You can use WillCascadeOnDelete which requires a migration (* if you did not implement it in the first place) or you can delete any related objects on your own.
Is it possible, in a code-first approach, to define two different context classes and use them simultaneously?
The database schema is already given and I cannot modify it (besides the creation of some new tables).
The problem I'm facing is that I'm getting "The model backing... has changed" error. It seems there's some kind of collision between the two contexts.
Note that each context includes a different set of tables, so sync problems aren't a concern.
Assuming you are using EF 6 or higher, this can be done either by the ContextKey-Property of DbMigrationsConfiguration (this will make the MigrationsHistory table multi tenant by ContextKey) or by setting HasDefaultSchema in OnModelCreating (this will enable multiple MigrationsHistory tables, one for each schema). For further instructions see the Documentation.
I have the following scenario:
I have a production database which is highly transactional. In order to keep queries efficient I would like to archive data from some of the tables to another database with exactly the same schema.
The relationships between tables are not very complex but any dependent objects would have to go with the archived data in order to uphold foreign key constraints.
Is there a simple way to do this using Entity Framework? I have tried to create two different contexts and add to one and delete from the other, but this is a bit of a tedious route.
If Entity Framework is not the best tool for this what is?
There is no simple way in EF5 to do this.
If your database is MSSQL you can make use of partitioning for archive tables (see http://blogs.msdn.com/b/felixmar/archive/2011/02/14/partitioning-amp-archiving-tables-in-sql-server-part-1-the-basics.aspx for more information).
I have a table that used throughout an app by Entity. I have a view that returns an identical column set, but is actually a union on itself to try to work around some bad normalization (The app is large and partially out of my hands, this part is unavoidable).
Is it possible to have Entity 4 treat a view that is exactly like a table as the same type, so that I can use this view to populate a collection of the same type? This question seems to indicate it is possible in nhibernatem but I can't find anything like it for entity. It would be an extra bonus of the navigation properties could still be used to Include(), but this is not necessary (I can always manually join).
Since EF works on mappings from objects to database entities this is not directly possible. What you need is something like changing the queried database entity dynamically, and AFAIK this is not possible without manually changing the object context.
For sure the EF runtime won't care as long as it can treat the view as if it was completely separate table. The two possible challenges that I forsee are:
Tooling: Our wizard does allow you to select views when doing reverse engineering (i.e. database-first). Definitively if you can use 'code first against an existing database' you can just pretend that the view is just a table, but you won't get any help scripting the database creation or migrations.
Updates: in general you can perform updates for a view setting up store procedure mapping (which is available in the EF Designer from v1 or in Code First starting in EF6). You might also be able to make your view updatable directly or using instead off triggers (see "Updatable Views" here for more details). If I remember correctly the SQL generated by EF to retrieve database generated values (e.g. for identity columns) is not compatible in some cases with instead-off triggers. Yet another alternative is to have your application treat the view as read-only and perform all updates through the actual table, which you would map as a separate entity. Keep in in mind that in-memory entities for the view and the original table will not be kept in sync.
Hope this helps!