Ignore public/internal fields for NHibernate proxy - nhibernate

I have some entity types that I would like to lazy load. However, they have some internal (assembly) fields they expose, but are not used outside that class. These fields are compiler generated (F#) and I cannot change them. The an example exception is:
NHibernate.InvalidProxyTypeException:
The following types may not be used as
proxies: Mappings.MTest: field id#47
should not be public nor internal
I understand why NHibernate is doing this, and how having fields, if I accessed them, would mess up the lazy-loading properties of the proxies that are generated. However, since I know I won't be using the fields, can I override NHibernate somehow?
Is there any way I can say "ignore this field"? I'm using Fluent NHibernate, if that makes it easier.
Edit: I should also note, I'm using NHibernate 2.1.0 Alpha 2.
Edit2: The main gist here is that I want to keep LazyLoading enabled, which means I have to use the proxy generation. Disabling LazyLoading works (no proxies), but sorta defeats the purpose of a nice framework like NHibernate.

I reassembled NHibernate (easier than getting the source and rebuilding) and removed the code that errors on internal/public fields. LazyLoading appears to work just fine without that check. (Although, I'm new to NHibernate and so there are probably scenarios I don't know about.)
Edit:
Ah, there is a property, "use_proxy_validator" that will disable all validation checks. Good enough.
Fluently.Configure()
.ExposeConfiguration(fun cfg ->
cfg.Properties.Add("use_proxy_validator", "false"))...

Just set the lazy property to false,
<class name="OrderLine" table="OrderLine" lazy="false" >
you can read more in:
Must Everything Be Virtual With NHibernate? - http://davybrion.com/blog/2009/03/must-everything-be-virtual-with-nhibernate/
Ofir,
www.TikalK.com

You can use the
[XmlIgnore]
attribute to decorate the fields :)

Can you use an Interface to declare the fields "used" ?http://nhibernate.info/doc/nh/en/index.html#persistent-classes-poco-sealed
"Another possibility is for the class to implement an interface that declares all public members"
I don't know if NH use the same #transient annotation/attribute as the JAVA version to ignore a property in persistent operations.

You might want to take a look at this page which gives an overview of using F# with Fluent NHibernate.
Edit I just noticed your username. Am I correct in perhaps thinking that this is your blog? How foolish of me. It does seem to address your problem though, specifically "We start off by disabling LazyLoad because most of the properties are not virtual, and NHibernate will fail to validate the mapping. Instead, we explicitly LazyLoad things, like the Store reference."? Maybe I'm just misunderstanding the problem.

Related

Single repository with generic methods ... bad idea?

I'm currently trying out a few different ways of implementing repositories in the project I'm working on, and currently have a single repository with generic methods on it something like this:
public interface IRepository
{
T GetSingle<T>(IQueryBase<T> query) where T : BaseEntity;
IQueryable<T> GetList<T>(IQueryBase<T> query) where T : BaseEntity;
T Get<T>(int id) where T : BaseEntity;
int Save<T>(T entity) where T : BaseEntity;
void DeleteSingle<T>(IQueryBase<T> query) where T : BaseEntity;
void DeleteList<T>(IQueryBase<T> query) where T : BaseEntity;
}
That way I can just inject a single repository into a class and use it to get whatever I need.
(by the way, I'm using Fluent NHibernate as my ORM, with a session-per-web-request pattern, and injecting my repository using Structuremap)
This seems to work for me - the methods I've defined on this repository do everything I need. But in all my web searching, I haven't found other people using this approach, which makes me think I'm missing something ... Is this going to cause me problems as I grow my application?
I read a lot of people talking about having a repository per root entity - but if I identify root entities with some interface and restrict the generic methods to only allow classes implementing that interface, then aren't I achieving the same thing?
thanks in advance for any offerings.
I'm currently using a mix of both generic repositories (IRepository<T>) and custom (ICustomRepository). I do not expose IQueryable or IQueryOver from my repositories though.
Also I am only using my repositories as a query interface. I do all of my saving, updating, deleting through the Session (unit of work) object that I'm injecting into my repository. This allows me to do transactions across different repositories.
I've found that I definitely cannot do everything from a generic repository but they are definitely useful in a number of cases.
To answer your question though I do not think it's a bad idea to have a single generic repository if you can get by with it. In my implementation this would not work but if it works for you then that's great. I think it comes down to what works best for you. I don't think you will ever find a solution out there that works perfectly for your situation. I've found hybrid solutions work best for me.
I've done something similar in my projects. One drawback is that you'll have to be careful you don't create a select n+1 bug. I got around it by passing a separate list of properties to eagerly fetch.
The main argument you'll hear against wrapping your ORM like this is that it's a leaky abstraction. You'll still have to code around some the "gotchas" like select n+1 and you don't get to take full advantage of things like NH's caching support (at least not without extra code).
Here's a good thread on the pros and cons of this approach on Ayende's blog. He's more or less opposed to the pattern, but there are a few counter arguments too.
I've implemented such kind of repository for NHibernate. You can see example here.
In that implementation you are able to do eager loading and fetching. The pitfall is that with NH you will often need to be able to use QueryOver or Criteria API to access data (unfortunately LINQ provider is still far from being perfect). And with such an abstraction it could be a problem leading to leaky abstraction.
I have actually moved away from repository pattern and creating a unit of work interfaces - I find it limiting.
Unless you anticipate a change in the datastore i.e. going from DB to textfile or XML - which has never been the case for me, you are best off using ISession. You are trying to abstract your data access and this is exactly what NHibernate does. Using repository limits really cool features like Fetch(), FetchMany() futures etc. ISession is your unit of work.
Embrace NHibernate and use the ISession directly!
I've used this approach successfully on a few projects. It gets burdensome passing in many IRepository<T> to my Service layers for each BaseEntity, but it works. One thing I would change is put the where T : on the interface rather than the methods
public interface IRepository<T> where T : BaseEntity

mapping entities with relations backed by obfuscated fields with NHibernate

And here goes yet another question on NHibernate.
This one most likely doesn't have a desired answer, but still - let's give it a try.
I'm currently putting all the efforts into mapping a domain model onto the database using NHibernate. This domain model comes from a framework which is heavily obfuscated. (Not that I have worked a lot with obfuscated code before, but this one in most of the places can be translated neither by Reflector, nor by Resharper.)
Everything went more or less fine until I faced an entity with a required many-to-one relationship represented by a property with no setter with obfuscated backed field.
Is it possible to reference this obfuscated field somehow? A very special IPropertyAccessor?
If not, how can I load a fully constructed entity? The only option to inject a related object is by using a constructor that accepts it. But at the time of instantiating of an entity being loaded, neither IInstantiator nor IInterceptor has any data of it apart from the key. Any other extension points that suit my need?
To allow NHibernate to access your field instead of property you can use this in your mappings:
access="field"

Association in Nhibernate with Lazy true

I am working in a project that's work with N Hibernate. Due to performance issues and increasing in complexity of the project we need to do association manually in our code.As we all know for that we have to set lazy property true. What i want know that, is their any way to do association with set lazy property true.We have already created our own methods for filling Association.But still for that also we need to write many queries and code which is not satisfactory.
Please let me know some way for this.
Thanks.
Lazy loading is turned on by default. There is basically two ways how lazy loading is implemented by NHibernate.
Lazy loading of collections
Lazy loading of "single ended" references (many-to-one)
Collections are easy and straight forward. NHibernate uses its own implementation if the collection classes anyway, lazy loading is implemented there.
Single ended references ("normal" associations) are not that easy. Lazy loading is implemented in a proxy. The proxy is a class created at runtime which inherits from the referenced class. That's why everything in the referenced class needs to be virtual. The proxy overrides every member and makes sure that the data is loaded when a member is accessed from outside. The problem with the proxy is, if you reference a base class, you get a proxy from the base class and you can't downcast it to the real class. So be careful when using lazy loading with inherited classes.
Lazy is turned on by default, you need to explicitly turn it off. So you don't need to do anything special to get lazy loading.
When you are optimizing performance, also consider to use batch-fetching.
for single ended associations:
<class name="xx" batch-size="10">
and on collections:
<bag name="xx" .... batch-size="10">
it reduces the N+1 problem a lot (by factor of 10 in this example.).

Is it possible to use NHibernate without altering a DDD model that is part of a framework

I dig a lot of things about the DDD approach (Ubiquitous language, Aggregates, Repositories, etc.) and I think that, contrary to what I read a lot, entities should have behavior rather then being agnostic. All examples I see tend to present entities with virtual automatic properties and an empty constructor (protected or worst, public) and that's it. I consider this kind of objects more like DTOs then entities.
I'm in the process of creating a framework with its specific API and I don't want to be tied to an ORM. So I built the domain first (without thinking of persistence) and now I would like to use NHibernate as persistence tool so I added a new project to my current solution to help ensure that my model isn't altered to support NHibernate. This project should be an implementation of the abstract repositories that live inside my domain. And now the difficulties arise.
Since it is my first time with NHibernate (I'm also trying Fluent Nhibernate but it seems even more restricting) I would like to know :
Is it possible to use NHibernate without altering a DDD model that is part of a framework
The things (constraints) that are necessary for NHibernate to work as expected and efficiently (virtual properties, empty constructors, etc.) I think this list would be helpful to a lot of people who are starting to learn NHibernate.
Please keep in mind that I'm building a framework so the Open/Closed Principle is very important for me.
P.S.: Sorry if my english is not good, I'm from Montreal and I speak french.
Edit 1: Here is one problem I have with NHibernate now - How to map Type with Nhibernate (and Fluent NHibernate)
For NHibernate:
All mapped classes require a default (no-arguments) constructor. The default constructor does not have to be public (it can be private so that it is not a part of the API), but it must exist. This is because NHibernate must be able to create an instance of the mapped class without passing any arguments. (There are workarounds, but don't do that.)
All mapped properties for which lazy-loading will be required must be marked virtual. This includes all reference properties and all collection properties. This is because NHibernate must be able to generate a proxy class deriving the mapped class and overriding the mapped property.
All mapped collection properties should use an interface as the property type. For example, use IList<T> rather than List<T>. This is because the collections types in the .NET Framework tend to be sealed, and NHibernate must be able to replace a default instance of the collection type with its own instance of the collection type, and NHibernate has its own internal implementations of the collection types.
For NHibernate, prefer Iesi.Collections.Generic.ISet<T> to System.Collections.Generic.IList<T>, unless you are sure that what you want is actually a list rather than a set. This requires being conversant in the theoretical definitions of list and set and in what your domain model requires. Use a list when you know that the elements must be in some specific order.
Also note that it's typically not easy to swap object-relational mapping frameworks, and in many cases it is impossible, when you have anything beyond a trivial domain model.
The short answer to your question is that it is not possible, but if don't need lazy loading the required alterations are trivial.
No matter what, you will have add default constructors to classes that do not already have them. If you are willing to forgo lazy-loading, those default constructors can be private, and you don't have to make any other changes to your domain model to use NHibernate.
That's awfully close to persistence ignorance.
Having said that, if you want lazy-loading, you'll need to make several changes (outlined in other answers to this question) so that NHibernate can create proxies of your aggregated entities. I'm personally still trying to decide whether lazy-loading is an enabling technology for DDD or if it's a premature optimization that requires too many intrusive changes to my POCOs. I'm leaning toward the former, though I really wish NHibernate could be configured to use a specific constructors.
You might also take a look at Davy Brion's blog (I particularly liked Implementing A Value Object With NHibernate), which is really illuminating if you're interested in domain-driven-design and avoiding anemic domain models.
In my experience, the only thing that NHibernate requires of a domain is virtual properties and methods and a default no-argument constructor, which as Jeff mentioned, can be marked private or protected if need be. That's it. NHibernate is my OR/M of choice, and I find the entire NHibernate stack (NHibernate, NHibernate Validator, Fluent NHibernate, LINQ to NHibernate) to be the most compelling framework for persisting POCO domains.
A few things you can do with NHibernate:
Decorate your domain model with NHV attributes. These constaints allow you to do three things: validate your objects, ensure that invalid entities are not persisted via NHibernate, and help autogenerate your schema when using using NHibernate's SchemaExport or SchemaUpdate tools.
Map your domain model to your persistent storage using Fluent NHibernate. The main advantage, for me, in using FNH is the ability to auto map your entities based on conventions that you set. Additonally, you can override these automappings where necessary, manually write class maps to take full control of the mappings, and use the xml hbm files if you need to.
Once you buy into using NH, you can easily use the SchemaExport or SchemaUpdate tools to create and execute DDL against your database, allowing you to automatically migrate domain changes to your database when initilizing the NH session factory. This allows you to forget about the database, for all intents and purposes, and concentrate instead on your domain. Note, this may not be useful or ideal in many circumstances, but for quick, local development of domain-centric apps, I find it convenient.
Additionally, I like using generic repositories to handle CRUD scenarios. For example, I usually have an IRepository that defines methods for getting all entites as an IQueryable, a single entity by id, for saving an entity, and for deleting an entity. For anything else, NH offers a rich set of querying mechanisms -- you can use LINQ to NHibernate, HQL, Criteria queries, and straight SQL if need be.
Th only compromise you have to make is using NHV attributes in your domain. This is not a deal breaker for me, since NHV is a stand-alone framework which adds additional capabilities if you choose to use NHibernate.
I have built a few apps using NH, and each has a persistence ignorant domain with all persistence concerns separated into its own assembly. That means one assembly for your domain, and another for your fluent mappings, session management, and validation integration. It's very nice and clean and does the job well.
By the way: your English is pretty darn good, I wish my French was up to par ;-).
Just to put my two bits in, I struggled with the same thing once but I overcame this by:
Adding protected default constructor to every entity.
Making Id virtual
Let's take for example upvote and downvote for Vote entity on my experiment website:
http://chucknorrisfacts.co.uk/ (NHibernate + MySQL with Mono)
public class Vote : Entity
{
private User _user;
private Fact _fact;
// true: upvote, false: downvote
private bool _isupvoted;
// for nHibernate
protected Vote() { }
public Vote(User user, Fact fact, bool is_upvoted)
{
Validator.NotNull(user, "user is required.");
Validator.NotNull(fact, "fact is required.");
_fact= fact;
_user = user;
_isupvoted = is_upvoted;
}
public User User
{
get { return _user; }
}
public Fact Fact
{
get { return _fact; }
}
public bool Isupvoted
{
get { return _isupvoted; }
}
}
This class inherits from Entity where we stick all the minimum necessary for Nhibernate.
public abstract class Entity
{
protected int _id;
public virtual int Id { get {return _id;} }
}
and Fluent mapping where you Reveal the private property.
public class VoteMap : ClassMap<Vote>
{
public VoteMap()
{
DynamicUpdate();
Table("vote");
Id(x => x.Id).Column("id");
Map(Reveal.Member<Vote>("_isupvoted")).Column("vote_up_down");
References(x => x.Fact).Column("fact_id").Not.Nullable();
References(x => x.User).Column("user_id").Not.Nullable();
}
}
You could probably place protected default constructor in Entity class and configure nHibernate to use it instead but I didn't look into it yet.

Dependency injection with NHibernate objects

I am wondering how to tell NHibernate to resolve dependencies on my POCO domain objects.
I figured out that methods like CalculateOrderTax should be in the Domain object because they encode domain specific business rules. But once I have two of those I am violating SRP.
It would be no problem to extract those methods to Strategy classes, but I wonder how to make NHibernate load those.
It doesn't seem like a good solution to loop through a list of objects in the repository to do get/set based Dependecy injection before handing the object off to the higher layers.
I am also using Castle Windsor for my Depency injection right now.
I've been using interceptors for similar tasks:
An interceptor that modifies loaded entities:
public class MyInterceptor : EmptyInterceptor
{
public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types)
{
return InjectDependencies(entity as MyEntity);
}
}
Associate it with a session:
nhSessionFactory.OpenSession(myInterceptor);
I've also read somewhere that there would be better support for custom constructor injection in the upcoming 2.1 release but I can't seem to find the reference right now.
As no-one seems to be able to answer your question at the moment I thought I'd suggest restructuring your code to remove the need for the Order to calculate it's own tax.
You could delegate it to a OrderTaxService which takes an Order object and returns an OrderValue object or something along those lines.
This will keep the logic in your domain but remove the need to attach it to your Order objects.
I agree with Garry that you should remove service dependencies from your domain objects as much as possible. Sometimes it makes sense, such as encryption/decryption. In that case you can hide it in the infrastructure using interception or IUserType. I think the latter is favorable when you can use it. This article shows in detail how to do it. I am doing this and it works quite fine.