How to create mapping for a List<SomeNativeType> in FluentNhibernate? - nhibernate

I am trying to create a mapping file for the following Model using Fluent NHibernate. But, I am not sure of how to do the mapping for the List<<string>string> in the mapping file.
public class MyClass
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual List<string> MagicStrings { get; set; }
}
public class EnvironmentMapping : ClassMap<Models.Environment>
{
public EnvironmentMapping()
{
Id(x => x.Id);
Map(x => x.Name);
//HasMany(x => string) What should this be ?
}
}

This is not quite what you are asking, but I just want to point out that FNH Automapping will map your class with absolutely no further help from the programmer - i.e. you don't need additional Mapping classes.
You just have to declare the member as an IList, instead of a List. (Actually, I thought you had to use IList for regular FNH mapping too).
One further point - there was a bug with automapping value types such as strings and ints, which was fixed very recently, so make sure you're using the latest FNH builds if you decide to go the Automapping route (which I highly recommend, BTW!).

I found a solution for my problem, in my situation I have to create a separate table for MyStrings and have a foreign key relation with MyClass.

Related

Mapping class hierarchy through fluent nhibernate by using 2 strategies

I want to combine table-per-class and table-per-hierarchy strategies using fluent nhibernate or nhibernate itself(I mean hbm files), but I don't know how. I prefer fluent over hbm but if it's impossible, then hbm is also fine. I tested this by introducing Entity as ClassMap and all other as SubClassMap in fluent but then in hbm files generated by fluent, Entity was a class and all other were joined-classes which is not what I want. I will describe the problem in more detail below.
Class hierarchy:
public class Entity
{
public int ID { get; set; }
public string Name { get; set; }
}
public abstract class Person : Entity
{
public string Phone { get; set; }
}
public class SystemUser : Person
{
public string Password { get; set; }
}
I want to have one table for entity and one for person and all kinds of it(all its subclasses).I mean I want to use table-per-class strategy for Entity and table-per-hierarchy strategy for Person and SystemUser classes. Database structure is something like this:
EntityTable(ID(PK),Name)
PersonTable(EntityID(PK,FK),Phone,Password)
any help appreciated.
if EntityTable Id is not database generated (which is discouraged by NH anyways) you can use the trick
public PersonMap : ClassMap<Person>
{
public PersonMap()
{
Table("PersonTable");
Id(p => p.Id, "EntityID").GeneratedBy.HiLo("100");
DiscriminateSubClassesOnColumn("PersonType");
Map(x => x.Phone);
Join("EntityTable", join =>
{
join.KeyColumn("ID");
join.Map(p => p.Name);
});
}
}
public SystemUserMap : SubclassMap<SystemUser>
{
public SystemUserMap()
{
Map(x => x.Password);
}
}

What is the difference between Fluent Mapping and Auto mapping in Fluent NHibernate

After reading some of the articles about Fluent NHibernate I got confused from where to start
I have an existing database to which I need to create DataAccessLayer. I am new to NHibernate and FluentNhibernate. Since I understood that there is no need to write hbm.xml files, I picked Fluent Nhibernate.
So, What is FluentMapping? and AutoMapping?
I have created a classLibraryProject named FirstProject.Entities
I have created a class named "Customer"
namespace FirstProject.Entities
{
public class Customer
{
public virtual int CustomerID { get; set; }
public virtual string CustomerName { get; set; }
public virtual string Address1 { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual int Zip { get; set; }
}
}
Then I created a Mapping class
namespace FirstProject.Entities
{
public class CusotmerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(x => x.CustomerID).Column("CustomerID").GeneratedBy.Assigned();
Map(x => x.CustomerName);
Map(x => x.Address1);
Map(x => x.Address2);
Map(x => x.City);
Map(x => x.Zip);
}
}
}
I now don't know how to proceed further. Am I doing it right.. please suggest
how to configure and proceed further
The following is Fluent
Id(x => x.CustomerID).Column("CustomerID").GeneratedBy.Assigned();
I use Fluent assertions, like the following
actual.Should().BeGreaterThan(1).And().LessThan(2);
Fluent is basically where you chain together the commands such that it reads quite well.
Auto mapping is where you do nothing. Everything is done by conventions. I tend to use Auto. Fluent is nice if you don't follow conventions.
Based on your mapping, the CustomerId being Assigned is not the out-of-the-box convention. As such you need to either
Use Fluent to specify exactly how it should map. This is just like doing it the standard way in XML, but with a fluent interface.
Use Auto and specify a Convention that will automatically change CustomerId to be Assigned.
Use Auto and specify an Override, that will use Auto but override CustomerId to be Assigned.
If you want to do option 3, here is the code:
var model = AutoMap
.AssemblyOf<Customer>()
.Where(IsMapped)
.Override<Customer>(a => a.Id(b => b.CustomerId, "CustomerId").GeneratedBy.Assigned());
The function IsMapped must return True for entities you want to Map.

Mapping a backing field, that has a different type from the respective property, using Fluent NHibernate

I need to persist this class on database using Fluent NHibernate:
public class RaccoonCity
{
public virtual int Id { get; private set; }
public virtual DateTime InfectionStart { get; private set; }
private IList<Zombie> _zombies = new List<Zombie>();
public virtual IEnumerable<Zombie> Zombies
{
get { return _zombies; }
}
protected RaccoonCity()
{}
public RaccoonCity(DateTime startMonth)
{
InfectionStart = startMonth;
}
public virtual void AddZombie(Zombie z)
{
_zombies.Add(z);
}
}
The property has type IEnumerable to indicate that you shouldn´t use it to insert new items. The backing field is of IList to make it easy to insert new items from the own class.
Zombie is a simple class:
public class Zombie
{
public virtual int Id { get; private set; }
public virtual string FormerName { get; set; }
public virtual DateTime Infected { get; set; }
}
The map is the following:
public class RaccoonCityMap: ClassMap<RaccoonCity>
{
public RaccoonCityMap()
{
Id(x => x.Id);
Map(x => x.InfectionStart);
HasMany(x => x.Zombies)
.Access.CamelCaseField(Prefix.Underscore)
.Inverse()
.Cascade.All();
}
}
When I test this, the data is inserted in database, but the zombie´s foreign keys are empty, and the RaccoonCity instance has zero items on Zombies list.
You are declaring the relationship as Inverse, which means the Zombie and not the RacoonCity is responsible for maintaining the relationship.
Either add the corresponding reference to zombie and set it on the AddZombie method, or remove the Inverse (in that case, you'll see an INSERT with a null FK followed by an update).
Suggested reading: http://nhibernate.info/doc/nh/en/index.html#collections-onetomany
Found a post about it: https://web.archive.org/web/20090831052429/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/08/15/a-fluent-interface-to-nhibernate-part-3-mapping.aspx
I had to implement the method
HasManyComponent by myself since it
was missing in the actual trunk of the
framework. That is, it was not
possible to map a collection of value
objects. But it has not been that hard
since the source base is really nice.
My changes will probably be integrated
into the framework soon.
And this one:
http://nhforge.org/blogs/nhibernate/archive/2008/09/06/a-fluent-interface-to-nhibernate-part-3-mapping-relations.aspx

How to use Fluent NHibernate in N-Tier application?

I'm trying to adopt Fluent NHibernate with my project, currently I can get data from database, when I'm at application server, data is include its PK but when I return this data (as List) to client all of its PK is loose.
How can I fixed this problem?
Update
My POCO class is below: PKs are CountryCd and CityCd
public class coCity
{
public virtual string CountryCd { get; private set; }
public virtual string CityCd { get; private set; }
public virtual string CityNameTH { get; set; }
public virtual string CityNameEN { get; set; }
public virtual int DeliveryLeadTime { get; set; }
public virtual string CreateBy { get; set; }
public virtual DateTime CreateDate { get; set; }
public virtual string UpdateBy { get; set; }
public virtual DateTime UpdateDate { get; set; }
public override bool Equals(object obj)
{
return this.GetHashCode().Equals(obj.GetHashCode());
}
public override int GetHashCode()
{
return (this.CountryCd + this.CityCd).GetHashCode();
}
}
Mapping class:
public class coCityMap : ClassMap<coCity>
{
public coCityMap()
{
Table("coCity"); // this is optional
CompositeId()
.KeyProperty(x => x.CountryCd)
.KeyProperty(x => x.CityCd);
Map(x => x.CityNameTH);
Map(x => x.CityNameEN);
Map(x => x.DeliveryLeadTime);
Map(x => x.CreateBy);
Map(x => x.CreateDate);
Map(x => x.UpdateBy);
Map(x => x.UpdateDate);
}
}
Source code to get data at application server
public List<coCity> GetTest()
{
List<coCity> result = new List<coCity>();
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
result = (List<coCity>)session.CreateCriteria(typeof(coCity)).List<coCity>();
}
return result;
}
When its still at application server data is retrieve correctly as image below
alt text http://img138.imageshack.us/img138/1071/serverside.png
However when this data transit back to client side all of its PKs is loose like below.
alt text http://img203.imageshack.us/img203/1664/clientside.png
First of all, this isn't a problem with Fluent NHibernate so:
Serializable must be used on your POCO's when you serialize them.
(from your comment) NHibernate keeps a reference of the object retrieved from the database to a cache (1-st level cache). While you serialize this 'managed' object the output of the serialization is an unmanaged object. Nhibernate does not detect that a an object exists in the db just because you set an value in a newly constructed object. You must get the object from the database and update its properties and call Update() or you work with pure sql with the object that returned from the client (yikes!).
Note that is irrelevant with this question: your Equals() implementation is really bad as it doesn't take into account types and depends only on GetHashCode value. If all your classes have this implementation you could run into trouble.
I think the problem is with that private setter on the PK's properties. Try changing that to public.
Either way, mark your entity with Serializable
A few comments:
As a general recomendation when using nhibernate is to avoid composite Ids. Create on your model a surrogate Id that is an identity column and enforce uniqueness of CityCd and CountryCd somewhere else
When passing data around client/server tiers, consider using DTOs to avoid some commong LazyInitializationExceptions problems.

FluentNHibernate mapping for Dictionary

What is the best way of mapping a simple Dictionary property using Fluent NHibernate?
public class PersistedData
{
public virtual IDictionary<key, value> Dictionary { get; set; }
}
public class PersistedDataMap : ClassMap<PersistedData>
{
HasMany(x => x.Dictionary)
.Table("dict_table")
.KeyColumn("column_id")
.AsMap<string>("key")
.Element("value");
}
This will properly map Dictionary to table dict_table and use column_id to associate it to the base id.
As a side note, if you would like to use an Enum as the Key in the dictionary, it should be noted that NHibernate.Type.EnumStringType<MyEnum> can be used in place of the string in .AsMap<string> to use the string value instead of the Ordinal.
Using a simple class relationship such as the following:
public class Foo {
public virtual IDictionary<string, Bar> Bars { get; set; }
}
public class Bar {
public virtual string Type { get; set; }
public virtual int Value { get; set; }
}
You can map this with Fluent NHibernate in this way:
mapping.HasMany(x => x.Bars)
.AsMap(x => x.Type);
Where Bar.Type is used as the key field into the dictionary.
To map a list as a dictionary:
HasMany(x => x.Customers)
.AsMap();
I have not used it; so cannot give an example.
Have look at the wiki: Cached version of the page, Actual page I have given the cached version of the page as the site seems to be down.