Trigger logic in EF Code First implementation - c#

I have changed my MVC app database implementation from database first to code first. The only thing left is to move Triggers. I do not know where to put them. Should I put them in Repository and implement them in add/ edit / delete methods? Or maybe there is more appropriated place to execute triggers depending on repositories actions. Please let me any ideas of trigger implementation in Code First approach.

Can't offer loads of help here as I've never had to do it, but you could look at overriding DbContext.SaveChanges depending on how many triggers you're talking about...
Update Take a look at this question for a better example.

Related

Should I use Upsert IAction method or Edit and Create separately?

I'm new and learning how to build an MVC application and while implementing CRUD operations and I'm wondering if the logic from Edit and Create should be placed inside one single method as some tutorials seem to suggest.
Is this a good practice, and why?
Does this respect SOLID principles?
Thank you so much in advance <3
You could use the same request model for both create and update methods; however, they should still be separate endpoints for a few key reasons:
Security: You may want to implement additional controller logic around the editing of existing entities.
Different input required: To update an existing entity, you need to know the ID of the entity to be updated. Generally, this is passed in the form of a URL parameter in a PUT request. For example, to update user 2, you would send a PUT request to /api/users/2 with a request body containing the JSON of your create/edit user request model.
Clearer logging: By utilizing separate request types, it is much easier to interpret basic access logs. For example, if you see several 500 response codes in access logs for PUT requests, you are able to focus your investigation on the update logic.
With that said, there isn't really one right way. However, most development teams (including one-person teams) will opt for separate methods for some of the reasons above.

On table update, trigger an action in my .NET code

I'm wondering whether this is possible. We want a function to work in our .NET code when a value in a specific table is updated. This could be upon a record insert or update. Is this possible?
If not, is there an alternative process?
You need to ask a couple of questions.
Do you want any to none of your business logic at the db level?
Obviously a db trigger could do this (perform some action when a value is changed, even if very specific value only).
I've seen some systems that are db trigger heavy. Their 'logic' resides deeply and highly coupled with the db platform. There are some advantages to that, but most people would probably say the disadvantages are too great (coupling, lack of encapuslation/reusability).
Depending on what you are doing and your leanings you could:
Make sure all DAO/BusinessFunctoin objects call your 'event' object.function to do what you want when a certain value change occurs.
Use a trigger to call your 'event' object.function when a certain value change occurs.
Your trigger does everything.
I personally would lean towards Option 2 where you have a minimal trigger (which simply fires the event call to your object.function) so you don't deeply couple your db to your business logic.
Option 1 is fine, but may be a bit of a hassle unless you have a very narrow set of BF/DAO's that talk to this db table.field you want to watch.
Option 3 is imho the worst choice as you couple logic to your db and reduce its accessibility to your business logic layer.
Given that, here is some information toward accomplishing this via Options 2:
Using this example from MSDN: http://msdn.microsoft.com/en-us/library/938d9dz2.aspx.
This shows how to have a trigger run and call a CLR object in a project.
Effectively, in your project, you create a trigger and have it call your class.
Notice the line: [SqlTrigger(Name="UserNameAudit", Target="Users", Event="FOR INSERT")]
This defines when the code fires, then within the code, you can check your constraint, then fire the rest of the method (or not), or call another object.method as needed.
The primary difference between going directly to the db and adding a trigger is this gives you access to all the objects in your project when deployed together.
I have never tried this but it is possible. You can write a CLR assembly and call that from your table trigger.
You can see an example here.
But you should post your problem and you may find a better work around.

Batch update for RIA in SL5

c#
I need to update 4 objects (entities) that exits on a observableCollection.
if they are not bound to the view (UI)
What's the best way or How they should be updated using RIA?
I would not like to create 4 trips to the database.
Would this gerenate 4 sql update commands?
What about if there is a time frame while the User decides what to change, could be other user changing one of the entity. if so what?
Any links I could read related to these questions ?
thanks in advance
should at least know what kind of update you need to do, basing on your question I'm just assuming that you need the user to change some arbitrary values on some entities, so, no "optimizations" and Group update can be done.
The domaincontext will keep track of your changes and send them as a whole in single Changeset.
The number of trips that you'll do to the database it's not related to WCF Ria services, rather it's a feature of your data layer, however, if you are using an ORM like nHibernate take a look at it's batchsize, or for EF take a look at his extension: http://weblogs.asp.net/pwelter34/archive/2011/11/29/entity-framework-batch-update-and-future-queries.aspx
Normally yes. Any out of the box data layer solution I know of, will generate 4 distinct updates
this is known as Concurrency. Again, is something that you should manage at your data layer. Raising an exception if other user have changed that row is a reasonable way in most case
take a look at this http://blogs.infosupport.com/optimistic-concurrency-with-wcf-ria-services-and-the-entity-framework/
I suggest you to reformulate your question into more specific arguments. Actually it's too wide, each point requires analysis of your needs and it's impossible to indicate a way.

Auto Refresh Data In Entity Framework

I using visual studio 2010 and using Entity Framework, and SQL Server 2008 R2. I have after trigger on my table, and When Save one record in table, another column in other table changed.
Is it possible to change automatically changed record on my application.
There is an InsertOnSubmit event that fires as noted here, not sure that's going to help you..
but there are various event fired when saving / modifying entities, but you'd have to bring your "trigger" logic into the code side, and then probably intelligently handle various Entity Changes.. here's more here : How To Execute Business Logic When Saving Changes
and after taking a deeper look at the title of your question it seems that you're trying to get the data from the updated table.. and as the comment suggests.. anything outside the scope of the entity "context" is going to have to be "reloaded". Now if that "loading" code is handled in your "change event" handling, you could accomplish this.. so why not just put all of that logic in your code layer? make the updates to your 2 "entities" and then save them in one swoop..
Though, not the answer you are after, I think you should move the "trigger" logic from the database to the application code. That will solve your problem, AND allow you to write a unit test verifying that data is updated correctly.
I Search for this question and find below code to refresh data in EF :
MyModelEntities.Refresh(System.Data.Objects.RefreshMode.StoreWins, TbMyRecord);

NHibernate & Cancelling Changes to Entities

This seems like it would be a common issue to be but I don't know the best way to solve it. I want to be able to send an Entity to a view, have changes be made to the entity in the view, but then cancel (remove) those changes if the user cancels out of the view. What is the proper way to do this.
Here are two options I have but I think there should be others that are better
1) Take an entity, create a clone, send the clone to the view...if changes are accepted, update the original entity with the clone's values
2) Send the entity to the view, if the user cancels, remove the entity from NHibernate's cache and reload it from the database
For (2), the issue for me would be that the old entity could still be referenced throughout my project after it has been removed from the cache.
Edit:
Ok, so the evict method is the way to go if I am implementing method (2). Thanks, I could not remember the details of that one. However, the issue of view objects referencing my old evicted entities makes the issue tough to deal with. I can't just have my view automatically update to a new entity without having custom code in each one to rebind when my custom eviction event is raised. And rebinding may not be trivial in certain cases. I need to think on this some more as I may be over complicating but at the moment, this method seems trickier.
I suspect I am going to be stuck with method (1) which has its own set of problems but will wait a bit longer to see if anyone else has some ideas.
Edit 2: Just found this. I think it pretty much covers the answer in detail and comes with a great demo project - Building a Desktop To-Do Application with NHibernate - http://msdn.microsoft.com/en-us/magazine/ee819139.aspx
In addition to this, NHibernate has a Session.Refresh(Object entity) function which seems to solve the exact problem. So, when an entity is changed but then cancelled before save, I can just call Session.Refresh to reload it from the database and discard the changes.
I'll go for option 1 and use what is called a ViewModel instead of your entity.
The ViewModel is representation of you model for a specific view. In the ViewModel you can mix data from different entities and pre-format values to fit the view. Is an elegant way of passing data to a view and you can accomplish what you want easily.
Using ViewModels is becoming the preferred way of working in ASP.net MVC and Silverlight / WPF.
To read more about Viewmodels: http://blogs.msdn.com/dphill/archive/2009/01/31/the-viewmodel-pattern.aspx
The best way to do this is to call the Evict method on the ISession used to load the object. This will remove the object from the session cache. and you can then reload and redisplay it.
Evicting the object from the session makes it transient detached so if there are still references to it in the project they will not be persisted when the session is flushed. How you deal with that depends on your application but I would suggest raising an event to notify subscribers that they need to re-load the object.

Categories

Resources