Is it possible to override the ObjectContext.SaveChanges method in entity Framework? - entity-framework

I was wondering if it is possible to override the ObjectContext.SaveChanges() method and write our own sql logic to save the changes made to the entities in the object context instead of relying on Entity Framework to save those changes in the database.

Generally you can do anything you want if you override SaveChanges and do not call base.SaveChanges but you will loose all the stuf EF will do for you. It means you will have to manually browse metadata and map your entities to SQL tables and columns. There will be like writing half the ORM yourselves.
If you just need some little custom logic when persisting entity you can map imported stored procedure to Insert, Update and Delete operations in the entity designer.

In EF4 SaveChanges(SaveOptions) is virtual. You can override this method. MSDN

#Ladislav is correct that a stored proc is one way to do this (+1).
Another way is to write a wrapper provider.

Related

Entity Framework Core 2.0 Dynamically Creating A Database

I am new to EF Core, and as I tried using it I found out that you need to add migrations for it to create a database from models. My question is, do we have another option aside from migrations to dynamically create the database on run time just like what it was in EF 6?
Thanks.
Until a seeding mechanism is provided in EF Core you can provide your own seeding mechanism.
In earlier phases of a project, when the database is not yet fixed, I don't care that data get lost. When I want to recreate the database dynamically I call the function below. By the setting of a parameter I determine if this "recreateDatabase"-function is called yes or no. The function is included in MyOwnDbContext class.
The seed function you need to write is very similar to the one you use in EF 6.
private static void recreateDatabase(YourOwnDbContext dbContext)
{
dbContext.Database.EnsureDeleted();
dbContext.Database.EnsureCreated();
seed(dbContext);
}

Entity Framework AddRange: how to map to stored procedure?

I am working with EF and stored procedures for data modification operations. So far I have been able to map stored procedures to basic operations such as Insert, Update, and Delete for one row (entity).
However, I would like to map also AddRange. I need a dedicate stored procedure for this operation and it does not work for me that EF calls my add stored procedure n times. I would like that it calls my AddRange stored procedures once.
I would also like to map another common tasks as Clear but for now AddRange is my top priority. Is this kind of mapping possible in EF? If not, is this something that would make sense to add or I am looking into the wrong direction?
I assume you are talking about AddRange which is an extension method of DbSet.
You can't map a store procedure to AddRange or Clear, because these methods are just preparing the entities and nothing will be added to database until SaveChanges is called.
If you need to Add multiple records with one db call, you can call it like this and not with DbSet
public class Context : DbContext
{
public void AddList()
{
this.Database.SqlQuery<YourEntityType>("storedProcedureName",params);
}
}

How to ExecuteSqlCommand in Entity Framework without it being contained in a transaction

I need to execute a stored procedure with Entity Framework.
Normally I call it like this:
this.Context.Database.ExecuteSqlCommand("EXEC edi_UploadTransmission");
However, this particular stored procedure includes accessing a linked server.
Since EF wraps ExecuteSqlCommand in a transaction, it is failing, as a linked server is not supported in a transaction (as far as I can tell).
Is there a way to execute this stored procedure with Entity Framework without it being in a transaction?
Pass TransactionalBehavior.DoNotEnsureTransaction as the first parameter to the ExecuteSqlCommand method.
For example,
this.Context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "EXEC edi_UploadTransmission");
My recommendation would be to simply not use EF for this part of your code. You can freely combine EF with straight ADO.NET code or with other ORMs such as Dapper or Chain.
https://github.com/docevaad/Chain/wiki/A-Chain-comparison-to-Dapper

How to run sql script on every EF migration

I want to run some custom Sql after every migration. I was hoping there was a global event or something I could tap into instead of putting my code in each individual migration.
What am I doing? I'm going to traverse the dbcontext via reflection to find enums to dump the key/values into an 'enum' table. The table won't be used anywhere, it's just for reference.
Thanks!
You can override the seed method of the configuration class: http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3

Entity Framework only with stored procedures

i have a question about the reasonableness of using entity framework only with stored procedures in our scenario.
We plan to have an N-tier architecutre, with UI, BusinessLayer (BLL), DataAccessLayer(DAL) and a BusinessObjectDefinitions(BOD) layer. The BOD layer is known by all other layers and the results from executes queries in the DAL should be transformed into Objects (definied in the BOD) before passing into the BLL.
We will only use stored procedures for all CRUD methods.
So in case of a select stored procedure, we would add a function import, create a complex type and when we execute the function, we tranform the values of the complex type into a class of BOD and pass that to the BLL.
So basicly, we have no Entities in the Model, just Complex types, that are transformed into Business Objects.
I'm not sure if that all makes sense, since in my opinion, we lose a lot of the benefit, EF offers.
Or am i totally wrong?
I would not use EF if all I was just using was stored procs.
Personally, I'd look at something like PetaPoco, Massive or even just straight Ado.Net
EDIT
Here's an example of PetaPoco consuming SPs and outputting custom types
http://weblogs.asp.net/jalpeshpvadgama/archive/2011/06/20/petapoco-with-stored-procedures.aspx
I disagree with both of the existing answers here. Petapoco is great, but I think the EF still offers a number of advantages.
Petapoco works great (maybe even better than the EF) for executing simple stored procedures that read a single entity or a list of entities. However, once you've read the data and need to begin modifying it, I feel this is where the EF is the clear winner.
To insert/update data with petapoco you'll need to manually call the insert/update stored procedure using:
db.Execute("EXEC spName #param1 = 1, #param2 = 2")
Manually constructing the stored procedure call and declaring all the parameters gets old very fast when the insert/update stored procedures insert rows with more than just a couple of columns. This gets even worse when calling update stored procedures that implement optimistic concurrency (i.e. passing in the original values as parameters).
You also run the risk of making a typo in your in-lined stored procedure call, which very likely will not be caught until runtime.
Now compare this to the entity framework: In the EF I would simply map my stored procedure to my entity in the edmx. There's less risk of a typo, since the entity framework tools will automatically generate the mapping by analyzing my stored procedure.
The entity framework also will handle optimistic concurrency without any problems. Finally, when it comes time to save my changes the only step is to call:
entities.SaveChanges()
I agree, if you rely on stored procedures for all CRUD methods, then there is no need to use EF.
I use EF to map stored procedure calls as our DAL. It saves time in writing your DAL by mapping the functions. We are not using LINQ to SQL as much, as our DBA does not want direct data table access.