Programming to interfaces while mapping with Fluent NHibernate - c#

I have been whipped into submission and have started learning Fluent NHibernate (no previous NHibernate experience). In my project, I am programming to interfaces to reduce coupling etc. That means pretty much "everything" refers to the interface instead of the concrete type (IMessage instead of Message). The thought behind this is to help make it more testable by being able to mock dependencies.
However, (Fluent) NHibernate doesn't love it when I try to map to interfaces instead of concrete classes. The issue is simple - according to the Fluent Wiki, it is smart to define the ID field of my class as for instance
int Id { get; private set; }
to get a typical auto-generated primary key. However, that only works with concrete classes - I can't specify an access level on an interface, where the same line has to be
int Id { get; set; }
and I guess that negates making the setter private in the concrete class (the idea being that only NHibernate should ever set the ID as assigned by the DB).
For now, I guess I will just make the setter public and try to avoid the temptation of writing to it.. But does anyone have an idea of what would be the "proper", best-practice way to create a proper primary-key field that only NHibernate can write to while still only programming to interfaces?
UPDATED
From what I understand after the two answers below from mookid and James Gregory, I may well be on the wrong track - there shouldn't be a reason for me to have an interface per entity as I have now. That's all well and good. I guess my question then becomes - is there no reason to program 100% against an interface for any entities? And if there is even a single situation where this could be justified, is it possible to do this with (Fluent) NHibernate?
I ask because I don't know, not to be critical. Thanks for the responses. :)

I realise this is a diversion, and not an answer to your question (although I think mookid has got that covered).
You should really evaluate whether interfaces on your domain entities are actually providing anything of worth; it's rare to find a situation where you actually need to do this.
For example: How is relying on IMessage any less coupled than relying on Message, when they both (almost) undoubtedly share identical signatures? You shouldn't need to mock an entity, because it's rare that it has enough behavior to require being mocked.

You can adjust your interface to contain only a getter:
public interface ISomeEntity
{
int Id { get; }
}
Your concrete class can still implement a setter as well, and since you are programming to your interfaces you will never call the setter "by accident".
If you want to disallow setting the id even when you hold a reference to a concrete instance, you can refrain from implementing a setter, and then let NHibernate access the field instead of the property - that's right, NHibernate can use some nifty reflection trickery to set your id field directly instead of invoking the property. Then you might map the id like this:
Id(e => e.Id).Access.AsCamelCaseField();
in which case your Id property must be backed by a corresponding id field. There are more naming conventions, e.g. if you prefer underscores as private field prefix.

I am having exactly the same issue.
Unfortunately I have a valid reason for using entity interfaces; the entity model will be implemented in different ways and with different mappings per customer.
The entire model needs to be read-only, so interfaces are of the style:
public interface IAccount
{
long AccountId { get; }
IHouse House { get; }
}
public interface IHouse
{
long HouseId { get; }
HouseStatus Status { get; }
IList<IAccount> Accounts { get; }
}
Concrete implementations then implement these with internal setters:
public class Account: IAccount
{
public virtual long AccountId { get; internal set; }
public virtual IHouse House { get; internal set; }
}
public class House: IHouse
{
public virtual long HouseId { get; internal set; }
public virtual HouseStatus Status { get; internal set; }
public virtual IList<IAccount> Accounts { get; internal set; }
}
I have gone down the route of mapping to the concrete classes. All is fine until you create relations which return interfaces and need to be cast to concrete implementations.
HasMany(x => x.Accounts)
can become
HasMany<Account>(x => x.Accounts)
But there is no equivalent 'cast' for
References(x => x.House)
Mapping to the interfaces (the neater solution) throws up the problem mentioned above in that the Id must exist on the topmost class for setting and requires a setter on the interface.
public sealed class AccountMap : ClassMap<IAccount>
{
public PokerPlayerMap()
{
Id(x => x.AccountId, "account_id");
DiscriminateSubClassesOnColumn("Type").SubClass<Account>(s =>
{
References(x => x.House);
});
}
}
For now, my only solution is to add setters to all of the interface Id fields. Its a shame the Id can't exist inside a subclass or have its type cast from the interface.

UPDATE: using union-subclass is not supported via the fluent interface fluent-nhibernate provides. You'll have to use a regular hbm mapping file and add it.
I too I'm trying do this with fluent NHibernate. I don't think it should be a problem mapping interfaces. You want to use an inheritance strategy, specifically the table-per-concrete-class strategy.
Essentially, you create a mapping definition for the base class (in this case your interface) and specify how to NHibernate should deal with implementers by using union-subclass.
So, for example, this should allow you to make polymorphic associations:
<class name="IAccountManager"
abstract="true"
table="IAccountManager">
<id name="Id">
<generator class="hilo"/>
</id>
<union-subclass
table="DefaultAccountManager"
name="DefaultAccountManager">
<property name="FirstName"/>
</union-subclass>
<union-subclass
table="AnotherAccountManagerImplementation"
name="AnotherAccountManagerImplementation">
<property name="FirstName"/>
</union-subclass>
...
</class>
Note how the Id is the same for all concrete implementers. NHibernate required this. Also, IAccountManager table doesn't actually exist.
You can also try and leverage NHibernate's Implicit Polymorphism (documented below the table-per-concrete-class strategy) - but it has tons of limitations.

Looks like I don't have enough reputation to comment on other peoples answers yet as such I'm going to have to make this an answer in it's own right.
References now has a generic overload to allow the cast that theGecko was looking for in his answer.

Related

Is there any utility that dynamically generates objects that implement interfaces at run time?

I've seen a ton of opensource frameworks that implement dynamic programming in C#. Is there one that can generate an implementation of an interface without there being any actual concrete class?
Specifically, suppose you have:
interface IThing {
int Id { get; set; }
string Name { get; set; }
}
And you also have objects you want to map into instances of IThing:
class Foo {
public int FooBarId { get; set; }
public string FooBarName { get; set; }
}
My hypothetical helper would let me write something like:
IThing concreteThing = helper.Implement<IThing, Foo>()
PropertyGetter(x => x.Id).Returns(foo => foo.FooBarId)
PropertyGetter(x => x.Name).Returns(foo => foo.FooBarName);
I suppose in my pretend example it would put exception throwing stubs into the setters of other properties I didn't supply...
I have an opensource framework ImpromptuInterface (in nuget) that given an interface, will generate stubs to DLR calls (recursively even). Which means you can add whatever logic you like behind it with an implementation of DynamicObject.
see this example.By using Reflection, you can avoid having to specify every possible Type within the implementation, but then you have other drawbacks:
The owner parameter do not expose any Type-information that is expected by the function. You need to check them manually.
Reflection overhead degrades performance on each call.
Reflection degrades maintainability (the method has to be implemented different).
Some operations (like Indexers) are tricky to handle with Reflection.In statically typed languages like C#, the interface of a class defines which operations are supported. A supported operation may be calling a method with a specified signature, or getting or setting a property, or be able to attach to a specific event. In most cases, this makes perfect sense, since the compiler is able to verify if the operations are supported by the specified type.

PetaPoco and Ignore attribute

I have the following class:
public class Foo
{
public int Id { get; set; }
...
public Boo Boo1 { get; set; }
public Boo Boo2 { get; set; }
}
I want to exclude Boo1 and Boo2 properties but I don't want to decorate those properties with PetaPoco.Ignore attribute. I want to have pure POCO objects. Can I execute Ignore command in code or do I have to create query/stored procedure and manually map all fields?
Any help would be greatly appreciated!
Looks like PetaPoco can't be told in any other way that fields/properties should be ignored than by using attributes. You can either Ignore a few members, or if you're not mapping the majority of a class then you can specify explicit column mapping for the class and decorate the ones you DO want mapped. I understand your hesitance to add ORM-specific cruft to a "pure" POCO, but unfortunately that information has to be somewhere, and as PetaPoco doesn't use mapping files (or much of a configuration at all, really), the class is where it goes.
The only thing you could do is create a DTO/DAO that will be what is mapped, then create implicit or explicit operators to convert between the domain class and its DTO. The DTO, then, can simply not have the fields you don't want to include. That keeps both classes POCO (depending on your feelings regarding operator methods), and it just adds a relatively simple step of casting the query result to your domain class.
In my branch here:
https://github.com/schotime/PetaPoco
You can fluently describe your models like I have described here: http://schotime.net/blog/index.php/2011/05/16/fluent-petapoco-external-mappings/ and also use the convention based mapping like here: http://schotime.net/blog/index.php/2012/02/13/petapoco-convention-based-fluent-mapping/
This is a great place for an anonymous type.
In your method for saving foo
public void InsertFoo(Foo f)
{
var db = new Database("connection");
var petaPocoFooObj = new {f.Id}
db.Insert("FooTable", "FooId", petaPocoFooObj);
}
It's just a little more work, although it could be a PITA if your classes are deeply nested.

I'm worried I'm adding too many interfaces

I am building out my domain model and continuing to refactor it. As I do, I am finding that I like interfaces as it allows me to create reusable methods/controllers/views for concrete types based on their interfaces. However, I am finding that I am creating an interface every time I add a new property to one of my domain entities.
For example, I have a MemberStatus object which inherits from an abstract Entity object which in turn implements the IIdentifiableEntity interface meaning that it has an Id property. MemberStatus also implements the INamedEntity interface meaning that it has a Name property, the IOrderedEntity interface meaning that it has a DisplayOrder property and the IHasMembers interface meaning that it has a collection Member objects. Here's the code:
public class MemberStatus : Entity, INamedEntity, IOrderedEntity, IHasMembers
{
public string Name { get; set; }
public float DisplayOrder { get; set; }
public ICollection<Member> Members { get; set; }
}
public abstract class Entity : IIdentifiableEntity
{
public int Id { get; set; }
}
public interface IIdentifiableEntity
{
int Id { get; set; }
}
public interface INamedEntity
{
string Name { get; set; }
}
public interface IOrderedEntity
{
float DisplayOrder { get; set; }
}
public interface IHasMembers
{
ICollection<Member> Members { get; set; }
}
Now, this seems to work fine as I other similar objects such as MemberPosition and MemberTeam which all implement these same interfaces and I can use my repository methods and controller actions with generics that implement these interfaces and have a lot of code reuse.
However, my concern is whether or not it's appropriate to keep adding simple, one-property interfaces every time I add a new property to my concrete objects. For example, let's say I want to add a bool Enabled property... should I continue to create a IEnabled interface? The reason I'm asking is that some of controller "initializers" that are using generics are becoming very long as shown in the following line of code. Is this normal and best-practice?
public abstract class OrderedCrudController<TEntity> : CrudController<TEntity> where TEntity : Entity, INamedEntity, IOrderedEntity, IHasMembers, new()
The fact that you are using interfaces is a good thing. However, you should ask yourself, if I create an IEnabled interface, will I ever reference my class by that interface alone? i.e. will there be contexts where I interact with my class purely via the single property that interface exposes?
Also, can you consider contexts where you will interact with multiple implementation of this IEnabled interface?
If the answer to both of these question is "no", then the interface serves very little purpose.
Having said that, please don't worry too much about this! it does very little harm.
Don't create interfaces that you don't foresee an imminent need for. Observe the YAGNI (you ain't gonna need it) principle. Otherwise you'll wind up with needlessly complicated code.
I think your problem is that you are trying to shoe-horn your domain model into whatever gui that you're displaying data in.
Instead, consider your domain object things that have behaviour close to data and in its c'tor, give it an Action<DomainEvent>. Now, make sure that you ONLY EVER pass data OUT from a domain object through this action.
Now, you listen. Whenever you actually want to make a change to your domain, call a method on it. Let your GUI be updated through the Action<DomainEvent> by taking these events and saving them to whatever read model that you are interested in.
Have a look at http://www.infoq.com/presentations/ddd-eric-evans and consider his points about domain events.
Now you don't have to add strange interfaces related to a technical domain into your business domain anymore. And remember; if you are doing CRUD like your examples show, then you are NOT doing domain driven design. You have an anemic domain.
Final point: use interfaces for things that actually need to be interchangeable. Are you carrying around a lot of INamed things in your application that can be interchanged with one another?
Let me also link this, for you to consider:
http://lostechies.com/jimmybogard/2011/10/11/event-sourcing-as-a-strategic-advantage/
http://lostechies.com/jimmybogard/2010/04/08/strengthening-your-domain-domain-events/

Should one use self-referencing generic inheritance like Customer : Entity<Customer>

Is it advisable to use self-referencing generic inheritance?
public abstract class Entity<T> {
public Guid Id {get; set;}
public int Version {get; set;}
public T Clone() {
...
// clone routine
...
return T;
}
}
public class Customer : Entity<Customer> {
public string CustomerName {get; set;}
...
}
How does one cast Customer to the base Entity class? What advantage does "Customer : Entity" provide? I see this kind of inheritance in examples showing NHibernate domain modeling.
Is it better to use "Customer : Entity" without the generics?
You should use it when you need it, not just because you can. In the example above, it makes some sense to implement Clone(). However, as you rightly point out, it means that your entity classes won't actually have a common base class, and properties that are truly common to them won't be accessible. The correct way to handle this is to split it in generic and non-generic parts:
public abstract class Entity {
public Guid Id {get; set;}
public int Version {get; set;}
}
public abstract class Entity<T> : Entity where T : Entity<T> {
public T Clone() {
...
// clone routine
...
return T;
}
}
Also, note the where part that I've added to declaration of Entity<T> - it ensures that this class can only be used as a part of this recursive pattern.
In the company i work for, the project I work on uses heavily this kind of trick. In fact, it is even promoted as a pattern in the code. Thus i can speak from experience: don't use it.
They may be cases where the self-referencing implementation is far simpler, more efficient and easier to read, but I have never encountered such a case. Heavy use of it makes code maintenance a nightmare, and in most cases can be avoided with only a normal inheritance and a casting of your method result if needed. And the performance cost of a casting into the derived class is negligible compared to the maintenance cost of your code.
So if you find the rare example where it is advisable to use self-referencing generic inheritance, go ahead and do so. But think twice beforehand, as there is probably a better way to do it.

Fluent nhibernate: How do I map an entity with a property who's type is an interface?

I have an entity like:
public class Employee
{
public int ID { get; set; }
public IAccountManager AccountManager { get; set; }
...
}
I also have a mapping defined for "DefaultAccountManager" - a concrete implementation of IAccountManager. When mapping the above "Employee" entity, how do I tell NHibernate to persist/load the AccountManager property using the mapping defined in "DefaultAccountManager"?
Edit:
Actually if I could setup a mapping for IAccountManager so that NHibernate could just infer which implementer to load/persist that would be even better. I'd rather not have to break polymorphism by forcing all implementers to use the same mapping.
I did find an answer to this one. I'm a little hazy on the details, as it was a few months ago, but the following was the jist of the solution:
Create a table for each implementation of IAccountManager that has mappings.
Make sure your DB is setup to use the HiLo id algorithm.
Use union-subclasses in your mappings
Union-subclasses would look something like this:
<class name="IAccountManager" abstract="true">
<id name="ID" column="ID" type="Int32">
<generator class="hilo"/>
</id>
<union-subclass name="DefaultAccountManager" table="DefaultAccountManager"
proxy="IAccountManager">
<property name="FirstName" type="String"/>
<property name="LastName" type="String"/>
</union-subclass>
... more implementations
</class>
Note the attribute "name" on union-subclass. This should be unique for (and match) each implementation of IAccountManager.
Also, the ID, instead of being unique to each table, will be unique to all IAccountManagers (by leveraging hilo).
When NHibernate sees an IAccountManager entity, it will use the instance's concrete type and the union-subclass definitions to figure out the correct table.
Hope this helps!
Just thought I would share a way that I managed to achieve this using Fluent NHibernate rather than the hbm files.
This method is a little hacky but the hacks are isolated and easily removed once Fluent NH gains proper support for Union-Subclass.
To use your example, the context of my scenario is this - the Employee class is in one project with the AccountManager property specified as an interface, because the concrete AccountManager is in a different project which we don't want to create a dependency to.
First I create a 'Helper' class that does most of the Employee mapping and looks like this.
public abstract class EmployeeMapperBase
{
protected abstract Type GetAccountManagerType();
public void DoMapping(ClassMap<Employee> classMap)
{
classMap.Id(x => x.Id);
classMap.Maps(..... etc....
classMap.References(x => x.AccountManager)
.Class(GetAccountManagerType());
}
}
Next, in the project with the concrete AccountManager class, I complete the mapping:
public class EmployeeClassMap : ClassMap<Employee>
{
public EmployeeClassMap
{
new ConcreteEmployeeMapper().DoMapping(this);
}
private class ConcreteEmployeeMapper : EmployeeMapperBase
{
public override Type GetAccountManagerType()
{
return typeof(DefaultAccountManager);
}
}
}
If you need polymorphism because the functionality of an IAccountManager implementation may have different functionality you could look at discriminators and use a base-class instead of an interface.
If you are just using an interface because they are the OOP paradigm du jour then think twice about it, with entities usually carrying little to no behavior an interface provides little -- if any -- value in a situation such as this.

Categories

Resources