Nullable GUID (Guid?) as the ID for Domain Class (NHibernate) - nhibernate

I am using Guid.comb for my primary key in my tables.
I never found any sample using nullable guid as the ID for the domain class; is this a bad practice with NHibernate?
The reason:
I am binding a list of POCO to combo box; without the nullable guid, I have to handle validation for Guid.Empty instead of using default build in DataAnnotations Required Validation.
Thanks you

The main reason for a primary key is that it defines a unique identifier for a particular record. If you were to be able to make your primary key nullable, then NHibernate would not be able to tell the difference between a newly created record with an empty GUID and a already existing record in your database with an empty or nullable GUID.
So yes, you do not see any examples of this because it would be a very bad practice.
In regards to your example of binding POCO's to a combo box, this is also a bad practice. Following the separation of concerns principle, you would not want to mix your UI logic with domain-specific logic such as the POCOs/entities that you are using with NHibernate to persist to the database. Typically, you would create a ViewModel class that would store whatever data is needed for the UI. You would then have a Service / Business layer which would store the business logic and handle converting/mapping your ViewModel classes to POCOs/entities/DTOs.
So in your example, if the application was following the separation of concerns principle, you would not even run into the issue you are facing because you would not be exposing the objects you wish to create/save/update using NHibernate. Separating your application in this way provides many other benefits such as not directly tying your database architecture to your UI, allowing you to easily modify the UI, Service Layer, or database without dramatically impacting any other layer, etc.

Related

Builtin objects with NHibernate

Does anyone know of a way to mix static object instances with those managed by NHibernate. I have an application where I use the repository pattern to manage db object instances, and those instances have some complex many-many, one-many, and many-one relationships. There are some scenarios where I'd like to have a guaranteed object (like a "User" type instance of "sys_user", for example). The instance must be able to participate in relationships, and I'm willing to have a hardcoded primary key for the few objects I want.
Basically I'm looking for a way to make my repository intermingle statically defined objects into the output, so if I ask for a list of "User"s i get the static "sys_user" plus those defined in the database. Furthermore, I'd like to be able to have that "sys_user" participate in a relationship with DB objects, i.e. - MyClass("db instance").UserProperty == "sys_user" instance, as defined by a fk on the MY_CLASS db table with a special value (say -1)
In essence, this is just a way to avoid an installation time requirement of pre-loading predefined objects that the app expects into the DB, as well as preventing them from being modified after installation. I want to code some logic that relies on special instances being present, and not allow users of the app to inadvertantly break that contract.
this should be exactly the case you describe, no need for repository though, just NHibernate http://fabiomaulo.blogspot.com/2009/08/from-db-to-ram-wellknowinstancetype.html

Entity Framework Code First DTO or Model to the UI?

I am creating a brand new application, including the database, and I'm going to use Entity Framework Code First. This will also use WCF for services which also opens it up for multiple UI's for different devices, as well as making the services API usable from other unknown apps.
I have seen this batted around in several posts here on SO but I don't see direct questions or answers pertaining to Code First, although there are a few mentioning POCOs. I am going to ask the question again so here it goes - do I really need DTOs with Entity Framework Code First or can I use the model as a set of common entities for all boundaries? I am really trying to follow the YAGNI train of thought so while I have a clean sheet of paper I figured that I would get this out of the way first.
Thanks,
Paul Speranza
There is no definite answer to this problem and it is also the reason why you didn't find any.
Are you going to build services providing CRUD operations? It generally means that your services will be able to return, insert, update and delete entities as they are = you will always expose whole entity or single exactly defined serializable part of the entity to all clients. But once you do this it probably worth to check WCF Data Services.
Are you going to expose business facade working with entities? The facade will provide real business methods instead of just CRUD operations. These buisness methods will get some data object and decompose it to multiple entities in wrapped business logic. Here it makes sense to use specific DTO for every operation. DTO will transfer only data needed for the operation and return only date allowed to the client.
Very simple example. Suppose that your entities keep information like LastModifiedBy. This is probably information you want to pass back to the client. In the first scenario you have single serializable set so you will pass it back to the client and client pass it modified back to the service. Now you must verify that client didn't change the field because he probably didn't have permissions to do that. You must do it with every single field which client didn't have permission to change. In the second scenario your DTO with updated data will simply not include this property (= specialized DTO for your operation) so client will not be able to send you a new value at all.
It can be somehow related to the way how you want to work with data and where your real logic will be applied. Will it be on the service or on the client? How will you ensure that client will not post invalid data? Do you want to restrict passing invalid data by logic or by specific transferred objects?
I strongly recommend a dedicated view model.
Doing this means:
You can design the UI (and iterate on it) without having to wait to design the data model first.
There is less friction when you want to change the UI.
You can avoid security problems with auto-mapping/model binding "accidentally" updating fields which shouldn't be editable by the user -- just don't put them in the view model.
However, with a WCF Data Service, it's hard to ignore the advantage of being able to write the service in essentially one line when you expose entities directly. So that might make the most sense for the WCF/server side.
But when it comes to UI, you're "gonna need it."
do I really need DTOs with Entity Framework Code First or can I use the model as a set of common entities for all boundaries?
Yes, the same set of POCOs / entities can be used for all boundaries.
But a set of mappers / converters / configurators will be needed to adapt entities to some generic structures of each layer.
For example, when entities are configured with DataContract and DataMember attributes, WCF is able to transfer domain objects' state without creating any special classes.
Similarly, when entities are mapped using Entity Framework fluent mapping api, EF is able to persist domain objects' state in database without creating any special classes.
The same way, entities can be configured to be used in any layer by means of the layer infrastructure without creating any special classes.

Persisting multiple DTOs mapped to a single entity

I guess this has been asked before here , but I'm still confused about the correct approach to be taken.
I have a WPF client application which talks to a WCF service to retrieve data.
On the Service side , I have a large entity ( around 25 properties) and I have
three forms in my client app .
On each form, I need the facility to edit certain properties of my domain entity.
I do not want to return the large entity through the service as I need just 3-4 of its properties on each form.
Hence I have created three DTOs ( we are using AutoMapper) , one for each screen.
The service returns DTOs and this works very fine as far as the retrieval goes.
My question is how do I persist my DTOs.
We are using NHibernate in the service layer.
If I pass my partial DTOs to the service to persist , I would need to reload my large entity every time to perform the update.
Is this the only way to handle this scenario ?
What other options do I have if I need to display partial views of one single entity on the UI .. besides sending across the whole entity over the wire ..or creating three DTOs?
Thanks.
Using NHibernate in the service layer it is logical that you will need to either:
a) load the entity during an update operation at the service, modify the required properties and then commit your transaction, or
b) if you have the object already available at the service (but not associated with the NHibernate session) then you can modify the required properties, call session.Update(obj) to reassociate the object with the session and then commit your transaction.
We use the first approach regularly where we have hundreds of different entities in our model. We pass specialised command request objects from client to server and then our service layer is responsible for performing the work specified in the command requests.
Alternatively you could formulate a HQL query as outlined here. But this will quickly get pretty ugly and difficult to maintain.

WCF and Inheritance

I'm working on a project where I have an abstract class of Appointment. There are Workouts, Meals and Measurements that all derived from Appointment. My architecture looks like this so far:
Dao - with data access layer being entity framework 4 right now
POCO classes using the T4 templates
WCF
Silverlight Client, ASP.net MVP, mobile clients
Would I put business rules in the POCO class? or map my Entities to a business object with rules and then map those to DTOs and pass those through WCF?? and when I pass the DTOs do I pass over type Appointment? Or write a service method for each sub class like Workout or Meal?
I haven't found any good material using table per type inheritance and WCF.
thanks in advance!
-ajax
it mainly depends on complexity you require. You are using POCO classes it is good starting point. You now have to choose how complex application are you going to build, how much business logic do you want to add and what do you want to expose to your clients?
The POCO entity can be just DTO or you can turn POCO entity into business object by adding business methods and rules directly into that entity - you will transform the entity into Active record pattern or to Domain object. I don't see any reason to map your POCOs to another set of business objects.
Exposing POCO entity in WCF service is the simplest way. You can use operations which will works directly with Appointment class. Additionally you have to give your service information about all classes derived from Appointment - check KnownTypeAttribute and ServiceKnownTypeAttribute. Using entity often means that service calls transport more than is needed - this can be problem for mobile clients with slow internet connection. There is one special point you have to be aware of when exposing entity which is aggregation root (contains references to another entitities and collection of entities) - if you don't have full control over client applications and you allow clients sending full modified object graph you have to validate not only each entity but also that client changed only what he was allowed to. Example: Suppose that client want to modify Order entity. You send him Order with all OrderItem entities and each item will have reference to its Product entity = full object graph. What happens if instead of modifing Order and OrderItems client changes any of Products (for example price)? If you don't check this in your business logic exposed by WCF and pass the modified object graph into EF context, it will modify the price in your database.
If you decide to use your entities like business objects you usually don't expose those entities, instead you will create large set of DTOs. Each operation will work with precisely defined DTO for request and response. That DTO will carry only information which are really needed - this will reduce data payload for service calls and avoid passing modified prices of product, because you will simply define your DTO to not transfer price or even whole product from the client. This solution is much more time consuming to implement and it adds additional layer of complexity.
Because I have mentioned object graphs I must clarify that there is another hidden level of complexity when using them: change tracking. EF context needs to know what have changed in object graph (at least which OrderItem was modified, which was added or deleted, etc.) for correct persistence. Tracking and multi tier solution is a chalenge. The simplest solution does not track changes and instead uses additional query to EF. This query returns actual persisted state of object graph and modified object graph is merged with it (special care is needed for concurrency checks). Other solutions uses some tracking support in entity - check Tracking changes in POCO and Self-tracking entities. But this is only for entities. If you want to track changes in DTO you have to implement your own change tracking. You can also read articles from MSDN magazine about multi tier applications and EF:
Anti-Patterns To Avoid In N-Tier Applications;
Building N-Tier Apps with EF4

Using NHibernate to determine which fields have been updated (for validation purposes) before persisting

Prior to persisting updates to my business entities, I need to perform validation checks to determine which properties have been changed. For example, certain fields can only be updated when the "Status" property has a particular value. E.g. when an Order entity has a Status of finalized, only the notes (string) field can be updated. Is this sort of thing possible using NHibernate, or should I be tracking the changes myself in the Business entities?
If I understand what you're trying to do, Gabriel's solution is not quite what you need. If it is not, you can try an event listener. Those allow you to hook into a common event (like on save) and do some processing before NHibernate finishes the save/insert/update/delete. Alternatively, you could look into using interceptors by implementing the IInterceptor interface.
This sort of thing is indeed possible. Coding Instinct has a great post introducing NHibernate.Validator.