How can I successfully map a many to many table in nhibernate with a composedID and still save to it directly? - nhibernate

I have a bunch of GUID constants in my code for certain tag categories that are important in my application. This is mapped in a simple two column many to many table. I often want to avoid fetching the nhibernate object because all I really need is the GUID and it's already hardcoded. I also noticed it's much quicker and easier to do certain queries with direct table access. So, the goal is to to map those nhibernate many to many tables as a class so they can be read and written to without disrupting nhibernates usage of them in the regular sense; while at the same time using GUIDs for identifiers.
Anyway, I have settled on using a composedID across the two columns nhibernate generates. But there is a problem. If I use composed ID and make a Category tag object and try to save my TagID and CategoryTag ID directly, TagID gets saved to the CategoryTagID column and CategoryTagID gets saved to the TagID column!
public class CategoryTagMapping : ClassMapping<CategoryTag>
{
public CategoryTagMapping ()
{
Table("CategoryTag");
/*Id(x => x.ID, map => map.Generator(Generators.Guid));*/
Property(x => x.CategoryTagID, map => { map.Column("CategoryTagID");});
Property(x => x.TagID, map => { map.Column("TagID"); });
ComposedId(p =>
{
p.Property(p1 => p1.CategoryTagID, a => a.Column("TagID"));
p.Property(p1 => p1.TagID, a => a.Column("CategoryTagID"));
});
}
}
public class CategoryTag
{
/*public virtual Guid ID {get;set;}*/
public virtual Guid CategoryTagID { get; set; }
public virtual Guid TagID { get; set; }
public override bool Equals(object obj)
{
if (obj == null)
return false;
var t = obj as CategoryTag;
if (t == null)
return false;
if (this.CategoryTagID == t.CategoryTagID && this.TagID == t.TagID)
return true;
return false;
}
public override int GetHashCode()
{
return (this.CategoryTagID + "|" + this.TagID).GetHashCode();
}
}
Trying to do this:
CategoryTag A = new CategoryTag { CategoryTagID = Constants.GUID1, TagID = Constants.GUID2 };
If I add the ID column by uncommenting the two lines, the saving works properly. But then that breaks the regular usage of the table because mysql can't auto increment the guid field and nhibernate won't generate an ID to go in the ID column.
Anyhow, maybe it's a bug, but maybe there's a workaround. Is there something wrong with the mapping, or the equals/gethashcode?
Thanks!

I am stupid. The columns are mismatched in the composedID mapping part.

Related

Nhibernate query for items that have a Dictionary Property containing value

I need a way to query in Nhibernate for items that have a Dictionary Property containing value.
Assume:
public class Item
{
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
}
and mapping:
public ItemMap()
{
HasMany(x => x.DictionaryProperty)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.AsMap<string>(
index => index.Column("IDNumber").Type<int>(),
element => element.Column("TextField").Type<string>().Length(666)
)
.Cascade.AllDeleteOrphan()
.Fetch.Join();
}
I want to query all Items that have a dictionary value of "SomeText". The following example in Linq fails:
session.Query<Item>().Where(r => r.DictionaryProperty.Any(g => g.Value == "SomeText"))
with error
cannot dereference scalar collection element: Value
So is there any way to achieve that in NHibernate? Linq is not an exclusive requirement but its preffered. Not that I'm not interested to query over dictionary keys that can be achieved using .ContainsKey . Φορ this is similar but not the same
Handling IDictionary<TValueType, TValueType> would usually bring more issues than advantages. One way, workaround, is to introduce a new object (I will call it MyWrapper) with properties Key and Value (just an example naming).
This way we have to 1) create new object (MyWrapper), 2) adjust the mapping and that's it. No other changes... so the original stuff (mapping, properties) will work, because we would use different (readonly) property for querying
public class MyWrapper
{
public virtual int Key { get; set; }
public virtual string Value { get; set; }
}
The Item now has
public class Item
{
// keep the existing for Insert/Updae
public virtual IDictionary<int, string> DictionaryProperty {get; set;}
// map it
private IList<MyWrapper> _properties = new List<MyWrapper>();
// publish it as readonly
public virtual IEnumerable<MyWrapper> Properties
{
get { return new ReadOnlyCollection<MyWrapper>(_properties); }
}
}
Now we will extend the mapping:
HasMany(x => x.Properties)
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.Component(c =>
{
c.Map(x => x.Key).Column("IDNumber")
c.Map(x => x.Value).Column("TextField")
})
...
;
And the Query, which will work as expected:
session
.Query<Item>()
.Where(r =>
r.Properties.Any(g => g.Value == "SomeText")
)
NOTE: From my experience, this workaround should not be workaround. It is preferred way. NHibernate supports lot of features, but working with Objects brings more profit

Losing the record ID

I have a record structure where I have a parent record with many children records. On the same page I will have a couple queries to get all the children.
A later query I will get a record set when I expand it it shows "Proxy". That is fine an all for getting data from the record since everything is generally there. Only problem I have is when I go to grab the record "ID" it is always "0" since it is proxy. This makes it pretty tough when building a dropdown list where I use the record ID as the "selected value". What makes this worse is it is random. So out of a list of 5 items 2 of them will have an ID of "0" because they are proxy.
I can use evict to force it to load at times. However when I am needing lazy load (For Grids) the evict is bad since it kills the lazy load and I can't display the grid contents on the fly.
I am using the following to start my session:
ISession session = FluentSessionManager.SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
I even use ".SetFetchMode("MyTable", Eager)" within my queries and it still shows "Proxy".
Proxy is fine, but I need the record ID. Anyone else run into this and have a simple fix?
I would greatly appreciate some help on this.
Thanks.
Per request, here is the query I am running that will result in Patients.Children having an ID of "0" because it is showing up as "Proxy":
public IList<Patients> GetAllPatients()
{
return FluentSessionManager.GetSession()
.CreateCriteria<Patients>()
.Add(Expression.Eq("IsDeleted", false))
.SetFetchMode("Children", Eager)
.List<Patients>();
}
I have found the silver bullet that fixes the proxy issue where you loose your record id!
I was using ClearCache to take care of the problem. That worked just fine for the first couple layers in the record structure. However when you have a scenario of Parient.Child.AnotherLevel.OneMoreLevel.DownOneMore that would not fix the 4th and 5th levels. This method I came up with does. I also did find it mostly presented itself when I would have one to many followed by many to one mapping. So here is the answer to everyone else out there that is running into the same problem.
Domain Structure:
public class Parent : DomainBase<int>
{
public virtual int ID { get { return base.ID2; } set { base.ID2 = value; } }
public virtual string Name { get; set; }
....
}
DomainBase:
public abstract class DomainBase<Y>, IDomainBase<Y>
{
public virtual Y ID //Everything has an identity Key.
{
get;
set;
}
protected internal virtual Y ID2 // Real identity Key
{
get
{
Y myID = this.ID;
if (typeof(Y).ToString() == "System.Int32")
{
if (int.Parse(this.ID.ToString()) == 0)
{
myID = ReadOnlyID;
}
}
return myID;
}
set
{
this.ID = value;
this.ReadOnlyID = value;
}
}
protected internal virtual Y ReadOnlyID { get; set; } // Real identity Key
}
IDomainBase:
public interface IDomainBase<Y>
{
Y ID { get; set; }
}
Domain Mapping:
public class ParentMap : ClassMap<Parent, int>
{
public ParentMap()
{
Schema("dbo");
Table("Parent");
Id(x => x.ID);
Map(x => x.Name);
....
}
}
ClassMap:
public class ClassMap<TEntityType, TIdType> : FluentNHibernate.Mapping.ClassMap<TEntityType> where TEntityType : DomainBase<TIdType>
{
public ClassMap()
{
Id(x => x.ID, "ID");
Map(x => x.ReadOnlyID, "ID").ReadOnly();
}
}

fluent nhibernate: compositeid() of same types, getting message no id mapped

I've scoured Google and SO but haven't come across anyone having the same problem. Here is my model:
public class Hierarchy
{
public virtual Event Prerequisite { get; set; }
public virtual Event Dependent { get; set; }
public override bool Equals(object obj)
{
var other = obj as Hierarchy;
if (other == null)
{
return false;
}
else
{
return this.Prerequisite == other.Prerequisite && this.Dependent == other.Dependent;
}
}
public override int GetHashCode()
{
return (Prerequisite.Id.ToString() + "|" + Dependent.Id.ToString()).GetHashCode();
}
}
Here is my mapping:
public class HierarchyMap : ClassMap<Hierarchy>
{
public HierarchyMap()
{
CompositeId()
.KeyReference(h => h.Prerequisite, "PrerequisiteId")
.KeyReference(h => h.Dependent, "DependentId");
}
}
And here is the ever present result:
{"The entity 'Hierarchy' doesn't have an Id mapped. Use the Id method to map your identity property. For example: Id(x => x.Id)."}
Is there some special configuration I need to do to enable composite id's? I have the latest FNh (as of 6/29/2012).
Edit
I consider the question open even though I've decided to map an Id and reference the 2 Event's instead of using a CompositeId. Feel free to propose an answer.
I figured out this was due to auto mapping trying to auto map the ID
Even though i had an actual map for my class - it still tried to auto map the ID. Once i excluded the class from auto mapping, it worked just fine.

NHibernate projecting a collection of elements

I want to select all requests that are outstanding for a given manager. A manager can have multiple teams.
I compose the queries applying various restrictions based upon permissions, and alter the queries to provide row counts, existence checks, sub queries, etc.
The composition makes use of QueryOver, though using ICriteria instead would also be acceptable.
Given the following classes;
class Team {
public virtual int Manager { get; set; }
public virtual ISet<int> Members { get; set; }
}
class Request {
public virtual int Owner { get; set; }
public virtual bool IsOutstanding { get; set; }
}
class static SomeRestrictions {
public static void TeamsForManager<TRoot> (this IQueryOver<TRoot, Team> query, int managerId) {
// In reality this is a little more complex
query.Where (x => x.Manager == managerId);
}
}
This is the current query that I'm trying (which doesn't work).
var users = QueryOver.Of<Team> ();
users.TeamsForManager (5)
users.Select (/* not sure */);
var requests = session.QueryOver<Request> ()
.Where (x => x.IsOutstanding)
.WithSubquery.WhereProperty (x => x.Owner).In (users);
The HQL to select the users would be:
"SELECT m FROM Team t JOIN t.Members m WHERE <TeamsForManager restrictions>"
But I don't want to use HQL because I can't then compose it with other restrictions based upon permissions. I also wouldn't be able to compose it with other queries to turn it into row counts/existence checks, etc.
i saw you changed the model but this would have been the way
var users = QueryOver.Of<Team> ();
users.TeamsForManager (5);
users.JoinAlias(t => t.Members, () => membervalue).Select(() => membervalue);

how to get id of entity using nhibernate createcriteria

Newbie Alert
I am trying to check if an entity exists in the database, if it does i want to update it else create a new entity. But CreateCriteria use always returns an entity with no id? Any ideas why? I am using fluent nhibernate for manual mapping i.e use of ClassMap;
Base class -hold only the Id public property
public abstract class EntityBase : IEquatable
{
public virtual int Id { get; set; }
public virtual bool Equals(EntityBase obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (GetType() != obj.GetType()) return false;
return obj.Id == Id;
}
}
MAPPING;
public class ProjectNameMap: ClassMap<ProjectName>
{
public ProjectNameMap()
{
Table("dbo.TABLENAME");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.PROJECT_NAME).Not.Nullable();
Map(x => x.PROJECT_DESCRIPTION);
}
}
Getting back the entity;
public static T GetEntityByRestrictions<T>(String propertyName, String propertyValue)
where T:EntityBase
{
using (var session = SessionManager.CreateSessionFactory().OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var entity= session.CreateCriteria<T>(propertyValue)
.Add(Restrictions.Eq(propertyName, propertyValue))
.UniqueResult<T>();
return entity;
}
}
}
}
Two silly steps i tried (dont laugh)
1. Silly step i tried was to manually set the Id =52 matching existing database entry and i keep on getting a primary key violation on project name as the database expects unique project name.
More silly steps (i can hear laughter) modified mapping file to include Map(x=>x.Id).Update().Insert() and this lead to INSERT_IDENTITY set to OFF (or somethin).
So whats the best way to get an entity with Id and update afterwards,is there something wrong with my CreateCriteria?
I believe calling the Merge method on the session will do exactly what you want.
Just put in the entity you want to update/insert as an argument and it will update the properties if the entity already exists or persist the new instance if it does not. This way you don't need the CreateCriteria and your solution will be a lot simpler.