nHibernate: determine property value before save - nhibernate

we are currently evaluating whether nHibernate supports the requirements for our project. We share the database with another application so that we are not completely free as regards changes to the schema.
Some columns are filled with unique and consecutive numbers (e.g. for invoices). The next number is determined by a stored procedure that also implements a locking algorithm so that the numbers are guaranteed to be consecutive.
On the one hand we could define a trigger on the respective tables that sets the value for the column when an empty or special value is provided. This would require changing the existing database definition - though it might be the most reliable way to implement this.
In order to avoid the change of the database definition we are trying to solve this in the nHibernate ORM. We've first tried to implement a user type that calls the stored procedure in NullSafeSet if an empty value is provided. Unfortunately, the connection and transaction of the provided command are not set yet when NullSafeSet is called.
How can we solve this with nHibernate?
Thanks in advance,
Markus

If you decide to go with trigger route, then you'll need to add generated attribute to your property mapping.
Generated properties are properties which have their values generated
by the database. Typically, NHibernate applications needed to Refresh
objects which contain any properties for which the database was
generating values. Marking properties as generated, however, lets the
application delegate this responsibility to NHibernate. Essentially,
whenever NHibernate issues an SQL INSERT or UPDATE for an entity which
has defined generated properties, it immediately issues a select
afterwards to retrieve the generated values.
Aside from that, I'm not quite sure how would you call stored procedure from NHibernate issued INSERT, without adding a trigger or default constraint on column.
Edit
Looks like NHibernate has a notion of class persisters, through the interface IEntityPersister. Maybe you could hack something out from that.
The persister attribute lets you customize the persistence strategy
used for the class. You may, for example, specify your own subclass of
NHibernate.Persister.EntityPersister or you might even provide a
completely new implementation of the interface
NHibernate.Persister.IClassPersister that implements persistence via,
for example, stored procedure calls, serialization to flat files or
LDAP. See NHibernate.DomainModel.CustomPersister for a simple example
(of "persistence" to a Hashtable).
You could start from NHibernate's source.
If you have the ability to add triggers to database, that would probably be the best, straightforward way, without investing too much time to fight with NHibernate's internals.

Related

Iterate over non null entities in model using linq

How do you iterate over the entities within a model in mvc 4 using entity framework 5.0? Looking for a more elegant process using linq.
Example: AnimalModel may have Cat, Dog, Pig entities. How would I detect just the entities and ignore other properties in the AnimalModel such as isHarry, Name, isWalking, isJumping. Is there a way to do this without using reflection, something within EF5 that allows for just looking at non-null entity values.
The main reason I am interested in this technique is to reduce code bloat and perform generic CRUD operations on the data across all entities and sub entities.
Possible Reference: link
I can't see how you can achieve this without using reflection at all.
You could try the following : Get all the EF types in the assembly which hosts them e.g.
var types = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == "NamespaceWhereEFEntitiesLive"
select t;
You may need to ply around a bit with the above query, but you get the idea.
You can then iterate through the properties of AnimalModel, check whether the property is of any type returned in types. e.g.
foreach(var prop in AnimalModelProperties) {
if (types.Contains(prop.GetType())
}
Note that the above for loop is a bit of a guess, but the pseudo-code should clarify what I'm looking to explain.
When you use EF to insert/update, it automatically ingores all irrelevant properties. If you want an implementation that takes properties from existing objects, then applies them to the database, you could use the relatively new upsert.
If you want a custom way to upsert a graph of objects...
If you are using either database-first or model-first (if you have an EDMX), you could use T4 templates to generate code that does this.
If you want this technique to support navigation properties, you will need some sort of assumption to prevent loops e.g. update from one to many, not the other way around and not many-to-many properties, or use the EDMX's optional description to place a hint on which navigation properties to visit.
Using reflection is a simpler solution, however, although, even with reflection you'll need to decide which way to go (e.g. using attributes (which you can get the T4s to add via the above assumptions/tricks)).
Alternatively, you could convert this technique (that I wrote) to work with EF, thus explicitly specifying where to visit in the graph in the using code, (using dbset.SaveNavigation(graph, listOfPropertyPaths) instead of writing complex code that assumes what you want it to do when you write dbset.Save(graph) (I have successfully done so in the past, but haven't uploaded it yet).
Also see this related article that I have recently found (I haven't tried it yet).
By the way, null properties do have significance in updating the database, often, you won't want to ignore them.

Does adding PetaPoco attributes to POCO's have any negative side effects?

Our current application uses a smart object style for working with the database. We are looking at the feasibility of moving to PetaPoco instead. Looking over the features I notice you can add attributes to make it easier to CRUD objects. Does adding these attributes have any negative side effects that I should be aware of?
Has anyone found a reason NOT to use these decorators?
Directly to the use of the POCO object instance itself? None.
At least not that I would be aware of. Jon Skeet should be able to provide more info because he knows compiler inner workings through and through, so he knows exactly what happens with this metadata after it's been compiled.
Other implications indirectly related to these
There are of course implications when accessing these declarative attributes, because they're read using reflection which is normally a slow process.
But there's nothing to worry here, because PetaPoco is a smart library and reads these only once then compiles & caches these things, so you only get penalized once then you get blazing performance afterwards. Because it uses compiled code.
Non-performance related implications
By putting attributes (any) on your classes/properties/methods you somehow bind your code to particular engine that will use this class, because they're directives for this particular engine to understand your code.
In case of PetaPoco attributes this means that your class can be used with PetaPoco but not with some other DAL (ie. EF) unless you add attributes of that one as well (EF Code First uses the very same approach with attributes).
The second implication is related to back-end database. In case you rename a table, column or any other part that is provided in your PetaPoco attribute as a constant magic string, you will subsequently have to change this string as well. This just means that you have to be thorough when doing database changes...
One downside is that it breaks the separation between the "domain" layer and the "data" layer, since it introduces the PetaPoco file (which contains data logic) to domain classes that should really not have any knowledge or dependency on the data layer.
If you're doing a single-project MVC app or something then it's okay to just use the Models directory for both, but for non-trivial and separated apps you'll have to have two PetaPoco files or play around with abstracting portions of the file in order to annotate your models without making them "know too much" about the underlying data, or else have you specify the table and/or primary key name all over the place.

Is it better to populate an object's properties in the constructor or when the property is referenced?

Background: I have an object with a dozen or so properties. The object is instantiated by passing a GUID to the constructor. This GUID is a primary key used to retrieve the property values from the database. Each property is stored in a separate table in the database. We are using EF4 to connect to the database.
Is it better to get all the properties at once from the database or is it better to fetch the property values from the database when the property is actually used in the code? What is the recommended best practice?
I would probably change the code to pass a Guid to a static factory method, which then did the lookup, and passed the recovered entity to the constructor. That way the constructor itself doesn't have to do as much work.
In most cases I would do all this eagerly though - it's usually odd to have an object which "feels" simple, but which then does potentially expensive and fallible database lookups when you access properties. And yes, you should strive to fetch everything in one database lookup - unless one of the properties is actually a collection in itself, etc. If it's just a case of fetching simple fields from the database, it would be crazy to perform one lookup per property access - which could end up giving inconsistent data, too.
At my job we use java / hibernate to handle the db related queries. You can configure it either way - lazy fetching waits for the application to request a property, or you can populate the object's properties on the initial query.
I'm not sure of a standard; however for our application we've found that populating the properties first turned out to be much faster. Its probably worth running a handful of tests to see how your application behaves - could be very different from ours.

How do I get the entity framework to work with archive flags?

I'm trying to create a set of tables where we don't actually delete them, but rather we set the archive flags instead. When we delete an entity, it shouldn't be deleted, it should be marked as archived instead.
What are the programming patterns to support this?
I would also prefer not to have to roll out my own stored procs for every table that have these archive flags if there is another solution.
This is an old question and it doesn't specify the EntityFramework version. There are a few good solution for newer versions:
Entity Framework: Soft Deletes Are Easy
Soft Delete pattern for Entity Framework Code First
Entity Framework 5 Soft Delete
Also there are sources for EF 6.1.1+
Highlights of Rowan Miller’s EF6/EF7 Talk at TechEd 2014
Entity Framework: Building Applications with Entity Framework 6
myEntity.IsArchived = true;
context.SaveChanges();
if your requirements are to not delete, then don't delete ;-)
You'll have to write your own logic to do this, and steer clear of the "MarkForDeletion" method on those entities.
Your logic will need to take a provided entity, alter it in some way to signify it is now "archived", and then Save the changes on the context.
You'll then need to make sure any code pulling from the DB honors these values that signify an archived record.
To make it simpler, you can create partial classes to match your entity classes, so they honor say, a custom interface. That way you can code against the interface and not have to use reflection to set the entity values.
If you can use .NET 4.0, EF supports POCOs and you can mark the entities natively with the appropriate interfaces, which will cut down the number of files you have to work with.
I'm not sure about best practices, but you might try writing your own DeleteObject method and putting it in a class of some sort (EFHelper is the name of the class I use for these sorts of things). Then instead of calling ObjectContext.DeleteObject, you call EFHelper.DeleteObject, and do any custom logic you care to do in that method. If you're consistent with the way you name these archive flag properties, you can use .NET's reflection API to find the archive_flag property of each EntityObject you're "deleting" and set it appropriately.

fluent nhibernate truncate string automatically

Is there an easy way to automatically truncate strings using fluent nHibernate mappings. I would prefer to not address this the setters or a custom type, but with something in the mapping files.
If I understand you correctly you want to make sure strings persisted to the database are no longer than a specified length. This sounds like it could be a business concern though and probably does belong in the domain model or as validation logic.
This question appears to have been asked before and the solution was a custom nHibernate UserType. Keep in mind this isn't a custom entity type or base class, this is a custom mapping type that nHibernate can understand.
Automatically truncating strings in NHibernate / SQL Server
If the custom usertype solution isn't to your liking then you could implement a custom interceptor, but I don't believe there is anything in nHibernate that does this "out-of-the-box". However, that is the beauty of nHibernate is that it is very extensible and implementing a custom user type for your situation is not difficult at all.