Can I have a collection of IUserType instances? - nhibernate

Is it possible to have a collection of entities that are mapped via an IUserType? For example:
class Foo
{
public int Id { get; set; }
public ISet<Special> Items { get; set; }
}
class Special
{
public Special(string columnValue)
{
_val = columnValue;
}
public override string ToString()
{
return _val.TranformInInterestingWays();
}
private string _val;
}
class SpecialUserTypeForMapping : IUserType
{
// assume that all the right stuff is here
// for using the non-default constructor on the way in
// and calling ToString() on the way out
}
If I'm reading the documentation correctly, neither the <set>, <one-to-many>, <many-to-many>, nor <class> element supports the "type" attribute as is used to apply IUserType mapping to <property>s. So how would I go about mapping this?

The most expedient solution seems to be to use the <element> element, like so:
<class name="Foo" table="foos">
<id name="Id" />
<set name="Items" table="foo_special">
<key column="fooId" />
<element column="special_value" type="SpecialUserTypeForMapping" />
</set>
</class>
Retrieving different Foo instances from the DB is no problem, but it's not clear whether it's possible to write queries against the special_value column, which is a requirement in my scenario. This question seems to indicate that it's not.

Related

Customization of nhibernate <set> querying

I want to get ClassA.ClassBCollection property filtered and paged. I need to change filtering dynamically.
The default querying will result in something like:
select * from ClassA
left outer join ClassB
on id == FK_ClassB
Can I customize querying of nhibernate set somehow?
Mappings:
<class name="ClassA">
<property name="Name" />
<set name="ClassBCollection">
<key column="FK_ClassB" on-delete="cascade" />
<one-to-many class="ClassB" />
</set>
</class>
<class name="ClassB">
<property name="Something"/>
</class>
If I do understand your question...
Can I customize querying of nhibernate set somehow?
...correctly, the answer is NO.
I mean, if you think about getting the instance of ClassA and doing some paging and filtering over its <set> collection. That would be always done in memory. (What we can do with mapping I appended at the end).
we can change the approach
In this case, when you need a filter and paging over the collection items, I would strongly recommend to go the other way. Create Criteria (QueryOver, HQL) not over the ClassA but over the ClassB.
First of all we have to extend ClassB mapping:
<class name="ClassB">
<property name="Something" />
<many-to-one name="ClassA" column="FK_ClassB" fetch="join" />
</class>
And then create a Criteria like this
var criteria = NHSession.Current.CreateCriteria<ClassB>();
criteria
.Add(new InExpression("ClassA", new object[] {1})) // id of one or more ClassA
.AddOrder(new Order("Something", true)) // Order By
.SetFirstResult(2) // Skip
.SetMaxResults(10); // Take
var list = criteria.List<ClassB>();
Because we used mapping of ClassA fetch="join" the resulting SQL statement will be very similar to the first snippet in this question.
So this way, we can achieve the desired SQL Select, but we cannot use ClassA.ClassBCollection directly. We did it this way...
NOTE:
Filters / paging which we can influence on the <set> mapping are static filter in the where clause and style of fetching values.
Where clause will always be evaluated when loading ClassBCollection as a property of the ClassA. It could be like where="IsActive=true"
In case that ClassA can have a lot of items in ClassBCollection, we can manage how they will be loaed. Very effective way is attribute batch-size documented here
Can I customize querying of nhibernate set somehow?
I'm not entirely sure what this means. If you meant, can I query and use WHERE clauses over the collection, the answer is yes. Here's how:
[TestFixture]
public class StackOverflowQuestion13496270Tests
{
public ISession session;
[SetUp]
public void SetUp()
{
session = // Get the current NHibernate session
}
[Test]
public void Query_ClassA()
{
var results = session.Query<ClassA>()
.Where( x => x.ClassBCollection.Any( y => y.Name == "Bob" ) )
.Fetch( x => x.ClassBCollection )
.Skip( 0 )
.Take( 50 )
.ToList();
}
[Test]
public void Query_ClassB()
{
var results = session.Query<ClassB>()
.Where( x => x.Name == "Bob" )
.Fetch( x => x.ClassAParent )
.Skip( 0 )
.Take( 50 )
.ToList();
}
public class ClassA
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<ClassB> ClassBCollection { get; set; }
}
public class ClassB
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
// Add this and the appropriate mapping modifications to be able to navigate back to the parent
public virtual ClassA ClassAParent { get; set; }
}
}

Composite Id's and Restrictions.IdEq or with comparison in Linq not working as expected

I have an entity where a composite id is used. I changed to code to make use of wrapping the composite id in a seperate key class. I expected that with Linq I could do a comparison on key object and with the Criteria API to use Restrictions.IdEq but both fail. I need to explicitly compare the key values to make it work.
I cannot find any documentation if this should work so for the moment I am stuck with direct comparisons but this means that when I alter the key that I also need to update the query code which is obviously not what I would want.
As a side note, I tried this with NHibernate 3.0.0 Alpha 2 and 3.
Domain
Mapping
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="Cwc.Pulse.Dal"
namespace="Cwc.Pulse.Dal">
<class name="AddonStatus">
<composite-id name="Id">
<key-many-to-one name="Context" column="Context_Id" class="Context" />
<key-property name="AddonType" column="Addon_Id"/>
</composite-id>
<property name="Status" />
</class>
</hibernate-mapping>
Class
public class AddonStatus
{
public virtual string Status { get; set; }
public virtual Key Id { get; protected set; }
public AddonStatus()
{
Id = new Key();
}
public class Key
{
public virtual Context Context { get; set; }
public virtual AddonType AddonType { get; set; }
public override int GetHashCode()
{
return ContextId.GetHashCode() ^ AddonType.GetHashCode();
}
public override bool Equals(object obj)
{
if (this == obj) return true;
var o = obj as Key;
if (null == o) return false;
return Context == o.Context && AddonType == o.AddonType;
}
}
}
Working queries
The queries below work and as you can see I compare the key values explicitly. I do not compare the key object.
Linq
from status
in session.Query<AddonStatus>()
where status.Id.Context == context && status.Id.AddonType == addonType
select status
Criteria API
session.CreateCriteria<AddonStatus>()
.Add(Restrictions.Eq("Id.Context", context))
.Add(Restrictions.Eq("Id.AddonType", addonType))
Expected to work but dont
I expect the following queries to work. Either in efficiently for linq in memory instead of the database but I expect the criteria api to be smart enough to handle such composite id´s in queries.
Both linq and criteria api queries make use of a Key object comparison.
var key = new AddonStatus.Key
{
Context = context,
AddonType = addonType
};
Linq
from status
in session.Query<AddonStatus>()
where status.Id == key
select status
Criteria API
session.CreateCriteria<AddonStatus>()
.Add(Restrictions.IdEq(key))
So if anyone has such a scenario working then what am I doing wrong?
Not directly an answer to your question, but it may be useful to you anyway. You could avoid the (explicit) composite key by mapping the AddonStatus as composite-element on the owner (most probably the Context):
<class name="Context">
<map name="AddonStates" table="AddonStatus">
<key column="Context_Id" /> <!-- Foreign key to the Context -->
<index column="Addon_Id" /> <!-- Dictionary key -->
<composite-element>
<property name="Status" /> <!-- data -->
</composite-element>
</map>
</class>
In the class Context is looks like this:
class Context
{
IDictionary<AddonType, AddonStatus> AddonStates { get; private set; }
}
This results and pretty the same database structure, but it is different to work with. I can't say if this is what you actually want, but it just looks like it.
Interestingly, I'm getting almost the exact opposite of this behavior in 2.1.2.
My mapping (simplified):
<!-- Subscriber class -->
<class name="Subscriber" >
<composite-id name="SubscriberKey" class="SubscriberKey">
<key-property name="Request" column="RequestID" type="int"/>
<key-many-to-one name="User" column="UserID" class="User" not-found="ignore" />
</composite-id>
<!-- User class - note that this goes to a different schema,
and is not mutable. Who knows if that's important... -->
<class name="User" schema="AnotherDb.dbo" mutable="false">
<id name="Id" column="UserID" type="int">
<generator class="native" />
</id>
<property name="FirstName" column="FirstName" type="string" />
<property name="LastName" column="LastName" type="string" />
goes to:
public class User
{
public virtual int? Id {get; protected set;}
public virtual string FirstName { get; protected set; }
public virtual string LastName { get; protected set; }
public User() { }
}
public class Subscriber
{
public virtual SubscriberKey SubscriberKey { get; set; }
public virtual User User { get; set; }
public Subscriber() { }
}
public class SubscriberKey
{
public override bool Equals(object obj)
{
if (obj is SubscriberKey && obj != null)
return ((SubscriberKey)obj).Request == Request
&& ((SubscriberKey)obj).User.Id == User.Id;
return false;
}
public override int GetHashCode()
{
return (Request.ToString() + User.Id.ToString()).GetHashCode();
}
public virtual int Request { get; set; }
public virtual User User { get; set; }
public SubscriberKey() { }
}
Things which work:
CreateCriteria<Subscriber>()
.Add(Restrictions.IdEq(keyInstance))
.UniqueResult<Subscriber>();
CreateCriteria<Subscriber>()
.Add(Restrictions.Eq("SubscriberKey.User.Id", aUserID))
.Add(Restrictions.Eq("SubscriberKey.Request", aRequestID))
.UniqueResult<Subscriber>();
Things which don't work:
Get<Subscriber>(keyInstance);
I'm thinking this is an inconsistency between their various ID-equaling query forms. When I get time, I'll be building a minimal unit test to submit as a bug example. I'd be interested in any / all thoughts anyone might have on this...
edit: Heeey, I figured it out!
Things which do work, now that I've read this
Get<Subscriber>(new SubscriberKey() {
User = Load<User>(aUserID), // the important part!
Request = aRequestID
});
This will create a proxy object for the User key, without hitting the database (unless necessary). If you swap Load<User> for Get<User>, you'll immediately hit the database to populate the object, rather than respecting your lazy-loading properties. Use Load.
And things like this are precisely why people suggest the (type)Repository pattern - I can do this behind the scenes: Get<>(new SK(){User=Load<>(key.User.Id)}, and still Get(key) by a single key, identical to every other object.

Automapping conventions for when Property and backing field have NOTHING in common?

Using Fluent NHibernate, I cannot seem to devise the necessary automapping conventions for the following (seemingly simple and common) use-case:
public class MyClass
{
private int _specialIdentityField
private string _firstname;
public Id { get { return _specialIdentityField; }; }
public virtual string Firstname
{
get
{
return _firstname;
}
set
{
_firstname = value;
}
}
}
public class OtherClass
{
private int _specialIdentityField
private string _lastname;
public Id { get { return _specialIdentityField; }; }
public virtual string Lastname
{
get
{
return _lastname;
}
set
{
_lastname = value;
}
}
}
The desired mappings are like so:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="field.camelcase-underscore" auto-import="true" default-cascade="none" default-lazy="true">
<class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="MyClass" table="`MyClass`">
<id name="_specialIdentityField" type="System.Int32" access=field>
<column name="Id" />
<generator class="identity" />
</id>
<property name="Firstname" type="System.String">
<column name="Firstname" />
</property>
</class>
<class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="OtherClass" table="`OtherClass`">
<id name="_specialIdentityField" type="System.Int32" access=field>
<column name="Id" />
<generator class="identity" />
</id>
<property name="Lastname" type="System.String">
<column name="Lastname" />
</property>
</class>
</hibernate-mapping>
Basically the rules are:
everything is field-camelcase-underscore as an access type EXCEPT identity
identity is a fixed-name field in every class (name=_someSpecialIdentityField)
identity access is always field-only and bears no relation to the name of the RO property that surrounds it
The part of this that is completely tripping me up is the convention-mapping of the identity-related elements (clearly the convention-mapping of the properties is completely standard fare). The issue I am having is how to tell FNH conventions that my identity field is a fixed-name. All of the convention overrides that I can find seem to assume there will always be some relationship between the property that represents identity and the name of its underlying backing field (e.g. I can set a 'custom prefix' for the backing field, but cannot seem to see how I can just say "this is always the name of the backing field").
Its obvious to me how to accomplish this with explicit mapping (and for that matter, with XML mapping files) but not obvious at all to me how to accomplish this with convention-based (Automapping) mapping in FNH.
This can't be an atypical use-case so I must just be overlooking something terribly obvious. Thoughts from any FNH gurus appreciated!
EDIT: Take a look at the IAutomappingConfiguration interface. Create you own implementation or override the DefaultAutomappingConfiguration class.
public virtual bool IsId(Member member)
{
return member.Name.Equals("id", StringComparison.InvariantCultureIgnoreCase);
}
then you add it to the initialization:
Fluently.Configure( Configuration )
.Mappings( cfg =>
{ cfg.AutoMappings.Add( IAutomappingConfigurationInstance )}
===============================================
Hi Steve, I think I know what you are trying to do. I use Proteus and FNH automapping. To do the trick with the id I created a wrapper around Proteus which do two things:
1) Maps the ID
2) Hides the Setter for the id
public abstract class EntityObject<TEntity> : IdentityPersistenceBase<TEntity, Guid>, IEntity
where TEntity : class, IEntity
{
public virtual Guid Id
{
get { return _persistenceId; }
}
Guid IIdentifiedEntity<Guid>.Id
{
get { return _persistenceId; }
set { _persistenceId = value; }
}
public virtual int Version
{
get { return _persistenceVersion; }
set { _persistenceVersion = value; }
}
}
And to avoid the property IsTransient to be persisted + other stuff you can create MappingAlternation:
public class EntityAlteration : IAutoMappingAlteration
{
public void Alter( AutoPersistenceModel model )
{
model.OverrideAll( map =>
{
Type recordType = map.GetType().GetGenericArguments().Single();
if( recordType.BaseType.Name == "EntityObject`1" )
{
Type changeType = typeof( Change<> ).MakeGenericType( recordType );
var change = ( IChange )Activator.CreateInstance( changeType );
change.Go( map );
}
} );
}
}
interface IChange
{
void Go( object mapObject );
}
class Change<TRecord> : IChange where TRecord : EntityObject<TRecord>
{
void IChange.Go( object mapObject )
{
var map = ( AutoMapping<TRecord> )mapObject;
map.Id( x => x.Id ).GeneratedBy.Guid().Access.Property();
map.IgnoreProperty( x => x.IsTransient );
}
}
PS: I am really missing the times when you were active in the online space. It was exciting Summer and Authumn 2 years ago...

NHibernate: Many-to-One - *Must* You Load the Parent Object?

Assume the following entity classes:
public class Player
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual Team Team { get; set; }
}
public class Team
{
public virtual int ID { get; set; }
public virtual string City { get; set; }
public virtual string Nickname { get; set; }
}
Assume the following mapping class for Player:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-lazy="false">
<class name="Player">
<id name="ID" column="ID" type="System.Int32" unsaved-value="null">
<generator class="native"/>
</id>
<property name="Name" column="Name" not-null="true" type="System.String" length="50" insert="true" update="true"/>
<many-to-one name="Team" not-null="true" outer-join="auto" insert="true" update="true">
<column name="TeamID"/>
</many-to-one>
</class>
</hibernate-mapping>
And assume the following Player repository method:
public void Add(Player player)
{
using (ISession session = NHibernateHelper.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(player);
transaction.Commit();
}
}
}
My question:
Must I load a full-fledged Team (parent object) when I want to create a new Player?
Or can I specify a "mock" object, and only specify the foreign key?
Player player = new Player
{
Name = "Tom Brady",
Team = new TeamRepository().GetTeamByCityAndNickname("New England", "Patriots") // Is this the only way?
// or can I do this?
// Team = new Team { ID = 22 }
};
new PlayerRepository().Add(player);
And if I can't specify a "mock"
object (specifying only the
foreign key), can you please explain
why I can't?
That is, can you please give me an idea about what's going on under the hood?
Heads-up:
A fellow had nearly the same question.
Here's the answer that made the most sense.
Interestingly, when speaking about EF
4.0 during a DotNetRocks episode, Julia Lerman
acknowledged that many people want to
use the foreign key in these types of
situations.
EDIT: This answer points to the essence of my question.
Think of it like having an object that
only keeps the Id and that will load
the rest if you ever need it. If
you're just passing it arround to
create relationships (like FKs), the
id is all you'll ever need.
Well if that's the case, then why do I need to be worried about proxy objects and such? Why can't I just create a "dummy" object and specify the foreign key value if that's all that really matters?
you use the foreign key like so...
Team = session.Load<Team>(id);
know the difference between load and get
If you have access to Session at this point you can call
Team = Session.Load<Team>(id);
The premise of Load is that it will create an NHibernate proxy that can resolve itself if needed. Of course you have to be sure the id exists or you will get an EntityNotFound error if it ever tries to resolve itself.

NHibernate: Many to Many relationship not working

I have the following database schema:
http://lh4.ggpht.com/_SDci0Pf3tzU/SdM3XnAmmxI/AAAAAAAAEps/Ie3xW3ZVNfQ/s400/styleerror.png
And this is my mapping file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="CodeSmithSampel.Generated.BusinessObjects" assembly="CodeSmithSampel">
<class name="CodeSmithSampel.Generated.BusinessObjects.Store, CodeSmithSampel" table="store" lazy="true">
<id name="Id" column="Id">
<generator class="native" />
</id>
<property name="Name" column="Name" />
<bag name="Employees" lazy="true" cascade="all-delete-orphan" inverse="true" >
<key column="Store_id"></key>
<one-to-many class="Employee"></one-to-many>
</bag>
<bag name="Products" table="storeproduct" lazy="true" cascade="all" inverse="true" >
<key column="Store_id"></key>
<many-to-many column="Product_id" class="Product" />
</bag>
</class>
</hibernate-mapping>
And ths is my Store entity class:
public partial class Store : BusinessBase<int>
{
#region Declarations
private string _name = String.Empty;
private IList<Employee> _employees = new List<Employee>();
private IList<Product> _products = new List<Product>();
#endregion
#region Constructors
public Store() { }
#endregion
#region Methods
public override int GetHashCode()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(this.GetType().FullName);
sb.Append(_name);
return sb.ToString().GetHashCode();
}
#endregion
#region Properties
public virtual string Name
{
get { return _name; }
set
{
OnNameChanging();
_name = value;
OnNameChanged();
}
}
partial void OnNameChanging();
partial void OnNameChanged();
public virtual IList<Employee> Employees
{
get { return _employees; }
set
{
OnEmployeesChanging();
_employees = value;
OnEmployeesChanged();
}
}
partial void OnEmployeesChanging();
partial void OnEmployeesChanged();
public virtual IList<Product> Products
{
get { return _products; }
set
{
OnProductsChanging();
_products = value;
OnProductsChanged();
}
}
partial void OnProductsChanging();
partial void OnProductsChanged();
#endregion
}
The product class:
public partial class Product : BusinessBase<int>
{
#region Declarations
private float _price = default(Single);
private string _name = null;
private IList<Store> _stores = new List<Store>();
#endregion
#region Constructors
public Product() { }
#endregion
#region Methods
public override int GetHashCode()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(this.GetType().FullName);
sb.Append(_price);
sb.Append(_name);
return sb.ToString().GetHashCode();
}
#endregion
#region Properties
public virtual float Price
{
get { return _price; }
set
{
OnPriceChanging();
_price = value;
OnPriceChanged();
}
}
partial void OnPriceChanging();
partial void OnPriceChanged();
public virtual string Name
{
get { return _name; }
set
{
OnNameChanging();
_name = value;
OnNameChanged();
}
}
partial void OnNameChanging();
partial void OnNameChanged();
public virtual IList<Store> Stores
{
get { return _stores; }
set
{
OnStoresChanging();
_stores = value;
OnStoresChanged();
}
}
partial void OnStoresChanging();
partial void OnStoresChanged();
#endregion
}
The mapping for the Product class:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="CodeSmithSampel.Generated.BusinessObjects" assembly="CodeSmithSampel">
<class name="CodeSmithSampel.Generated.BusinessObjects.Product, CodeSmithSampel" table="product" lazy="true">
<id name="Id" column="Id">
<generator class="native" />
</id>
<property name="Price" column="Price" />
<property name="Name" column="Name" />
<bag name="Stores" table="storeproduct" lazy="true" cascade="all" inverse="true" >
<key column="Product_id"></key>
<many-to-many column="Store_id" class="Store" />
</bag>
</class>
</hibernate-mapping>
What is particularly weird is that when I add a Store object to one of the product, the database record is not updated; the add doesn't seem to take place, although the new store object exists in the database:
IManagerFactory managerFactory = new ManagerFactory();
var productManager = managerFactory.GetProductManager();
var myProduct= productManager.GetById(2);
var myStore = new Store();
myStore.Name = "new Store"; //a "new store" entry is created in the Store table
myProduct.Stores.Add(myStore); // but this "new store" is not linked to the myproduct, as it should.
productManager.Session.CommitChanges();
Is there anything I miss?
Note: I generate the above code using CodeSmith.
Edit: The accepted answer works. The reason I got in this problem is because
Only one entity class should have inverse = true, not two. So either Product or Store should set the inverse to false. The code generation tool didn't handle this properly.
The correct way to Add Many to Many relationship is explained below. You must add two times.
Can this have anything to do with the fact that you have a surrogate key in the storeproducts table ?
What happens if you remove this surrogate key column Id, and put the primary key on the combination of the product_id and store_id columns ?
I believe that, if you want to have a surrogate key on the storeproducts table, you'll have to create yet another entity.
If you want to use the surrogate key, you'll have to use the idbag mapping.
How does your Product class and mapping look like ?
I see that you specify the 'inverse' attribute in your mapping of the Products collection in the Store entity.
If you do this (and thus you have a bi-directional association), then you should add the Store to the Stores collection of the product as well.
Since -from the NH documentation- :
Changes made only to the inverse end
of the association are not persisted.
This means that NHibernate has two
representations in memory for every
bidirectional association, one link
from A to B and another link from B to
A. This is easier to understand if you
think about the .NET object model and
how we create a many-to-many
relationship in C#:
category.Items.Add(item); // The category now "knows" about the relationship
item.Categories.Add(category); // The item now "knows" about the relationship
session.Update(item); // No effect, nothing will be saved!
session.Update(category); // The relationship will be saved
The non-inverse side is used to save
the in-memory representation to the
database. We would get an unneccessary
INSERT/UPDATE and probably even a
foreign key violation if both would
trigger changes! The same is of course
also true for bidirectional
one-to-many associations.
You may map a bidirectional
one-to-many association by mapping a
one-to-many association to the same
table column(s) as a many-to-one
association and declaring the
many-valued end inverse="true".
This means, that only one of the ends should be inverse.
Adding a Product to a store, should be done like this:
public class Store
{
public void AddProduct( Product p )
{
if( _products.Contains (p) == false )
{
_products.Add (p);
p.AddStore(this);
}
}
}
public class Product
{
public void AddStore( Store s )
{
if( _stores.Contains (s) == false )
{
_stores.Add (s);
s.AddProduct(this);
}
}
}
(Very important to check whether the collection already contains the item to be added; otherwise you'll end up in an infinite loop.