nHibernate mapping for entity to multiple different parent entities (eg Addres -> Firm, Addres -> Client) - nhibernate

Can someone help me with the best way to map the following situation in fluent nHibernate? The Address class is used in both Client and Company. How can I store it most efficient in SQL? And what should the mapping look like? I've thought about multiple options, but I'm not experienced enough with nHibernate for these situations:
use 1 address entity and 1 table and use a denominator column to distinguish between address for client and address for company -> how to implement this in nHibernate?
use 1 address entity and 2 tables (ClientAddresses and CompanyAddresses) --> but I can only define 1 table in the mapping of the class Address
use 2 address entities and 2 tables --> not so elegant
I've just stumbled upon this problem when I started implementing the company class and realized it also needed multiple addresses. Up till now I had a Address and Client class and had a one-to-many mapping between them. In the database the Address had an extra column called ClientId. But with introducing the Company class I'm stuck...
Any help would greatly be appreciated.
I'm currently working in the sharparch 1.5 framework, which uses automapping and my mapping files are like this:
public class AddressMap : IAutoMappingOverride<Address>
{
public void Override(AutoMapping<Address> mapping)
{
mapping.Table("addresses");
mapping.Id(x => x.Id, "AddressGuid")
.UnsavedValue(Guid.Empty)
.GeneratedBy.GuidComb();
mapping.References(x => x.Client, "ClientGuid");
}
}
Below some more code the illustrate the problem:
Address
public class Address
{
public virtual string StreetLine1 { get; set; }
public virtual string StreetLine2 { get; set; }
public virtual string PostalCode { get; set; }
public virtual string City { get; set; }
public virtual string Country { get; set; }
}
which has the following table:
tablename = addresses
fields= AddressGuid, StreetLine1, StreetLine2, PostalCode, City, Country
Client
public class Client
{
public IList<Address> Addresses {get;set;}
}
Company
public class Company
{
public IList<Address> Addresses {get;set;}
}

It looks like you can implement #1 with nHibernate's <any> mapping. Note that in this case you cannot specify foreign-key constraints.
an example of <any>
Fluent nHibernate syntax

You could model the relationships as a many-to-many: many companies to many addresses, and many clients to many addresses.
In both your Company and Client mappings:
mapping.HasManyToMany(x => x.Addresses);
This will create two additional tables: one mapping between companies and addresses, another mapping between clients and addresses.
In theory this could allow sharing situations (some companies and clients all sharing have the same address row) which you probably don't want, but as long as your application logic doesn't allow that to happen, you'll be fine and you won't have to do anything tricky with nhibernate.

Related

Mapping to a different view based on child type

So i have a situation where i have common base type but i need to map to a different view based on the child type.
It looks like i can use a generic mapping class to handle the inheritance
http://geekswithblogs.net/nharrison/archive/2010/07/09/inheriting-a-class-map-in-fluent-nhibernate.aspx
But how can i conditionally map to a different view based on the child type? I see an EntityType property but it says its obsolete and will be made private in the next version.
As an example i have a base class of ContactInfo is standard between contact types but the values come from different places depending on the contact type, this I'll handle through the sql view.
using any mapping the referenced entity comes from a different table
class ContactInfo
{
public virtual long Id { get; set; }
public virtual ContactDetails Details { get; set; }
}
public ContactInfoMap
{
...
ReferencesAny(x => x.Details)
.EntityIdentifierColumn("details_id")
.EntityTypeColumn("contactType")
.IdentityType<long>()
.AddMetaValue<FooContactDetails>("1")
.AddMetaValue<BarContactDetails>("4");
}

How can I model this object hierarchy in Fluent NHibernate without violating DDD principles?

I am trying to build a domain model that will allow me to manage Contracts.
The Contract class is my aggregate root, and it has a single property right now, which is Reviewers.
Reviewers, in the context of the Contract, each have a property to it's parent Contract, and a First Name, Last Name, and Login. The reason they have these properties is so I can have the user select which Reviewers they want on a Contract.
The database that I'm tying my domain model to already exists, and it's a legacy system that I'm trying to extend.
It has a Contract Table, and a Reviewer Table.
The thing I haven't mentioned up until this point, is that Reviewers are actually Users in the system. So there's actually a third table involved, which is Users.
I have been able to map my Contract Table easily with FNH.
It looks something like this:
public class ContractMapping: ClassMap<Contract>
{
public ContractMapping()
{
Id(c => c.Id);
HasMany(c => c.AdditionalReviewers);
}
}
But I'm not sure how to model my Reviewers, because they are in fact Users as well. So my object model looks like this:
public class Reviewer: User
{
public virtual Guid Id { get; set; }
public virtual Contract Contract { get; set; }
}
public class User
{
public virtual Guid Id { get; set; }
public virtual string Login { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
I've been able to map my User class properly, and it looks something like this:
public class UserMapping: ClassMap<User>
{
public UserMapping()
{
Id(u => u.Id);
Map(u => u.Login);
Map(u => u.FirstName);
Map(u => u.LastName);
}
}
and I believe I want to map my Reviewer class like this:
public class ReviewerMapping: SubclassMap<Reviewer>
{
public ReviewerMapping()
{
Table("Reviewer");
//Id(r => r.Id).Column("ReviewerId"); <- won't compile
References(r => r.Contract).Column("ContractId");
}
}
So the problem I'm having is this:
The relationship between the User table and the Reviewer table is one to many. Meaning, for a given User there may be many Reviewer records. Why? Because a User has to be a Reviewer for a specific Contract. This causes an issue with the mapping, though, because the primary key for my Reviewer and the primary key for my User are completely different values, by necessity.
Also, because of the way I'm using Reviewer, when I create a new Reviewer, what I'm really trying to do is to associate a User with a Contract. I am not trying to create an entirely new User in the database.
What is the correct way for me to map Reviewer, knowing that in my domain model it is a subclass of User?
Sounds like a the Reviewer is not really modelling a person, but modelling a role or assignment the User takes on. I'd say your domain model is flawed in this aspect. Tweak Reviewer to be an association class between a User and a Contract.
I don't think Reviewer should inherit from User in the scenario you've described. I would have the Reviewer class hold a User object instead (composition over inheritance).
If it helps you conceptualize it better, rename Reviewer to Review. That way you can stop thinking about it as a User since it really isn't (multiple Reviewers in your current domain can be the same User, which doesn't make much sense).

Fluent NHibernate & one-to-one

For a (very) long time I've been looking for an example on how to correctly implement a one-to-one mapping with Fluent NHibernate.
Most resources I find say:
I think you mean a many-to-one
However no one actually gives an example on how to correctly implement the one-to-one relation.
So, could you give an one-to-one mapping example with Fluent NHibernate?
Note: I'm not interested in people saying "what's your model, you might actually need HasMany". No, thanks, I simply need a one-to-one example.
To be more precise, I know the syntax. That's the only thing I could find by searching by myself. What I'm looking for is a more complete example, including a ((very) simple) database setup, and the whole mapping, of all entities that participate in the relationship, which I think would have reasonable size for Stack Overflow.
I've solved my problem.
I've also written a somewhat detailed article on this problem, that you can find at: http://brunoreis.com/tech/fluent-nhibernate-hasone-how-implement-one-to-one-relationship/index.html
You will find a scenario in which we want a one-to-one relationship, the database schema as we would like it, the code of the model as it needs to be to meet NHibernate requirements, and the Fluent mapping that corresponds to the situation.
these are the two classes.
public class A
{
public virtual int Id {get;set;}
public virtual string P1 {get;set;}
public virtual string P2 {get;set;}
public virtual string P3 {get;set;}
public virtual B child { get; set; }
}
public class B
{
public virtual int Id {get;set;}
public virtual string P4 {get;set;}
public virtual string P5 {get;set;}
public virtual string P6 {get;set;}
public virtual A parent;
}
this should be added in the fluent configuration.
public AMap()
{
/* mapping for id and properties here */
HasOne(x => x.child)
.Cascade.All();
}
public BMap()
{
/* mapping for id and properties here */
References(x => x.parent)
.Unique();
}
This is the best example I've seen. Hopefully it meets your needs.
HasOne(x => x.Prop)

Question about Repositories and their Save methods for domain objects

I have a somewhat ridiculous question regarding DDD, Repository Patterns and ORM. In this example, I have 3 classes: Address, Company and Person. A Person is a member of a Company and has an Address. A Company also has an Address.
These classes reflect a database model. I removed any dependencies of my Models, so they are not tied to a particular ORM library such as NHibernate or LinqToSql. These dependencies are dealt with inside the Repositories.
Inside one of Repositories there is a SavePerson(Person person) method which inserts/updates a Person depending on whether it already exists in the database.
Since a Person object has a Company, I currently save/update the values of the Company property too when making that SavePerson call. I insert / update all of the Company's data - Name and Address - during this procedure.
However, I really have a hard time thinking of a case where a Company's data can change while dealing with a Person - I only want to be able to assign a Company to a Person, or to move a Person to another Company. I don't think I ever want to create a new Company alongside a new Person. So the SaveCompany calls introduce unnecessary database calls. When saving a Person I should just be able to update the CompanyId column.
But since the Person class has a Company property, I'm somewhat inclined to update / insert it with it. From a strict/pure point of view, the SavePerson method should save the entire Person.
What would the preferred way be? Just inserting/updating the CompanyId of the Company property when saving a Person or saving all of its data? Or would you create two distinct methods for both scenarios (What would you name them?)
Also, another question, I currently have distinct methods for saving a Person, an Address and a Company, so when I save a Company, I also call SaveAddress. Let's assume I use LinqToSql - this means that I don't insert/update the Company and the Address in the same Linq query. I guess there are 2 Select Calls (checking whether a company exists, checking whether an address exists). And then two Insert/Update calls for both. Even more if more compound model classes are introduced. Is there a way for LinqToSql to optimize these calls?
public class Address
{
public int AddressId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
}
public class Company
{
public int CompanyId { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Company Company { get; set; }
public Address Address { get; set; }
}
Edit
Also see this follow up question. How are Value Objects stored in a Database?
I myself have used the IRepository approach lately that Keith suggests. But, you should not be focusing on that pattern here. Instead, there are a few more pieces in the DDD playbook that can be applied here.
Use Value Objects for your Addresses
First, there is the concept of Value Objects (VO) you can apply here. In you case, it would be the Address. The difference between a Value Object and an Entity Object is that Entities have an identity; VOs do not. The VO's identity really is the sum of it's properties, not a unique identity. In the book Domain-Drive Design Quickly (it's also a free PDF download), he explains this very well by stating that an address is really just a point on Earth and does not need a separate SocialSecurity-like identity like a person. That point on Earth is the combination of the street, number, city, zip, and country. It can have latitude and longitude values, but still those are even VOs by definition because it's a combination of two points.
Use Services for combining your entities into a single entity to act upon.
Also, do not forget about the Services concept in the DDD playbook. In your example, that service would be:
public class PersonCompanyService
{
void SavePersonCompany(IPersonCompany personCompany)
{
personRepository.SavePerson();
// do some work for a new company, etc.
companyRepository.SaveCompany();
}
}
There is a need for a service when you have two entities that need both need a similar action to coordinate a combination of other actions. In your case, saving a Person() and creating a blank Company() at the same time.
ORMs usualyl require an identity, period.
Now, how would you go about saving the Address VO in the database? You would use an IAddressRepository obviously. But since most ORMs (i.e. LingToSql) require all objects have an Identity, here's the trick: Mark the identity as internal in your model, so it is not exposed outside of your Model layer. This is Steven Sanderson's own advice.
public class Address
{
// make your identity internal
[Column(IsPrimaryKey = true
, IsDbGenerated = true
, AutoSync = AutoSync.OnInsert)]
internal int AddressID { get; set; }
// everything else public
[Column]
public string StreetNumber { get; set; }
[Column]
public string Street { get; set; }
[Column]
public string City { get; set; }
...
}
From my recent experience of using the repository pattern I think you would benefit from using a generic repository, the now common IRepository of T. That way you wouldn't have to add repository methods like SavePerson(Person person). Instead you would have something like:
IRepository<Person> personRepository = new Repository<Person>();
Person realPerson = new Person();
personRepository.SaveOrUpdate(realPerson);
This method also lends itself well to Test Driven Development and Mocking.
I feel the questions about behavior in your description would be concerns for the Domain, maybe you should have an AddCompany method in your Person class and change the Company property to
public Company Company { get; private set; }
My point is; model the domain without worrying about the how data will be persisted to the database. This is a concern for the service that will be using your domain model.
Back to the Repository, have a look at this post for good explanation of IRepository over LinqToSql. Mike's blog has many other posts on Repositories. When you do come to choose an ORM I can recommend HHibernate over LinqToSql, the latter is now defunct and NHibernate has a great support community.

NHibernate one way, one-to-many, mapping question

I have a scenario in NHibernate where I have a one-to-many relationship between entities Employee and EmployeeStatus.
Employee has properties eg: ID, Name and an IList of EmployeeStatus, whilst EmployeeStatus, for the purposes of this question, just has it's own ID and some free text.
I don't need to hold a reference to Employee from EmployeeStatus, the management of status' will be done purely through the Employee entity - adding to the IList property. IE: I want to quite simply be able to do the following;
Employee e = new Employee();
e.Name = "Tony";
e.StatusList.Add( new EmployeeStatus("Status A") );
e.StatusList.Add( new EmployeeStatus("Status B") );
session.Save(e);
I've tried various methods, including creating a one way one-to-many mapping where inverse is false, cascade set to all-delete-orphan, which all looks like it should work, but it generates an exception about being unable to set the EmployeeId in EmployeeStatus. I'm led to believe that this is because NHibernate wants to do an insert with EmployeeId as NULL and then update it to the ID of the parent.
I guess I'm missing something here, so quite simply - can anyone tell me what my mapping file should look like to achieve the above?
Thanks in advance
Tony
-- edit: Heres a rough idea of the classes as requested --
public class Employee
{
private IList<EmployeeStatus> _statusList;
public Employee()
{
_statusList = new List<EmployeeStatus>();
}
public virtual int Id{ get; set; }
public virtual string Name{ get; set; }
public virtual IList<EmployeeStatus> StatusList
{
get
{
return _statusList;
}
}
}
public class EmployeeStatus
{
public virtual int Id{ get; set; }
public virtual string StatusText{ get; set; }
public EmployeeStatus()
{
}
public EmployeeStatus(string statusText)
{
StatusText = statusText;
}
}
The scenario you've described is just a basic one-to-many mapping. Here is the Fluent NHibernate mapping for this:
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
WithTable("Employee");
HasMany(employee => employee.StatusList)
.Cascade.All();
}
}
You do not need to maintain a reference from EmployeeStatus back to Employee to achieve this.
Turns out that what I want to do isn't possible - you have to have a bi-directional association, and must set the child's parent reference. Not a massive problem I suppose, but didn't want to hold references in the child that I don't need within my code directly.
I may not of explained clearly, but an employee status cannot be linked to more than one employee. It's definitely 1 (employee) to many (status')
In the physical database, the status entity has an employeeID field, which isn't in the domain - IE: I hold no reference back to employee from the status entity, but the physical field should be inferred from the owner of the collection - In fact, it does do this if I set the EmployeeID field in the status table to nullable - it actually executes 2 SQL statements - an insert and then an update, the EmployeeID being set in the update.
Thanks,
Tony
Can you post the code for the classes?
Are you trying to keep a history of statuses for an Employee?
-- Edit --
Looks like you are going to need many-to-many, since the child in the relationship (EmployeeStatus) has no reference back to the parent (Employee).
-- Edit 2 --
If you want the insert to be done as 1 call to the DB, you are going to need to add an Employee property to the EmployeeStatus class, and set the Inverse=true. And I'm pretty sure that you are going to need to add some logic which sets the bi-directional relationship in the objects. I.E.
public void AddStatus(EmployeeStatus status)
{
this.StatusList.Add(status);
status.Employee = this;
}