Nhibernate Mapping relationships on multiple columns - fluent-nhibernate

I'm having problems mapping a relationaship between two entities when there are two columns involved in the mapping.
I'm modelling a state machine with two object types - State and Transition. Each process has its own state machine, so States and Transitions need to be identified by ProcessId. My entity classes are like this:
public class State
{
public virtual long Id { get; set; }
public virtual int ProcessId { get; set; }
public virtual int Ordinal { get; set; }
public virtual Process Process { get; set; }
public virtual ICollection<Transition> TransitionsIn { get; set; }
public virtual ICollection<Transition> TransitionsOut { get; set; }
}
public class Transition
{
public virtual long Id { get; set; }
public virtual long ProcessId { get; set; }
public virtual int FromStateNum { get; set; }
public virtual int ToStateNum { get; set; }
public virtual long StateActionId { get; set; }
public virtual Process Process { get; set; }
public virtual StateAction StateAction { get; set; }
public virtual State FromState { get; set; }
public virtual State ToState { get; set; }
}
I need the navigation properties (State.TransitionsIn, State.TransitionsOut, Transition.FromState, Transition.ToState) to be based on the ProcessId and the Ordinal number of the state. For example, Transition.FromState should navigate to the entity where t.ProcessId = s.ProcessId and t.FromStateNum = s.Ordinal.
I've tried the following mapping, but it complains that I'm using two columns to map to one (StateId).
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumns.Add("ProcessId", "ToStateNum")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumns.Add("ProcessId", "FromStateNum")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "Ordinal");
References(t => t.ToState)
.Columns("ProcessId", "Ordinal");
}
}
How can I get this to work?

How about this mapping.. I have not tested it but just trying to give a direction.
public class StateMap : ClassMap<State>
{
public StateMap()
{
Id(x => x.Id);
HasMany(s => s.TransitionsIn)
.KeyColumn("ProcessId")
.KeyColumn("ToStateNum").PropertyRef("Ordinal")
.Inverse();
HasMany(s => s.TransitionsOut)
.KeyColumn("ProcessId")
.KeyColumn("FromStateNum").PropertyRef("Ordinal")
.Inverse();
}
}
public class TransitionMap : ClassMap<Transition>
{
public TransitionMap()
{
Id(x => x.Id);
References(t => t.FromState)
.Columns("ProcessId", "FromStateNum");
References(t => t.ToState)
.Columns("ProcessId", "ToStateNum");
}
}

Related

Fluent NHibernate Mapping multiple tables has relation and joined to each other

As you see the models have references as one to many. list of project is not mapped here. there are more than one project and the project has more than one role and the role has more than one permission.
error is persister system not avialable.
can anyone look up and help me ?
public class Permission
{
public virtual int MId { get; set; }
public virtual string Id { get; set; }
public virtual bool View { get; set; }
public virtual bool Add { get; set; }
public virtual bool Edit { get; set; }
public virtual bool Delete { get; set; }
public virtual Role Roles { get; set; }
}
public class Role
{
public virtual int RId { get; set; }
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Site_Id { get; set; }
public virtual string Site_Name { get; set; }
public virtual string Domain { get; set; }
public virtual List<Permission> permissions { get; set; }
public virtual Project Project { get; set; }
}
public class Project
{
public virtual int PId { get; set; }
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual List<Role> Roles { get; set; }
}
Mappings
public class PermissionMapping : ClassMap<Permission>
{
public PermissionMapping()
{
Table("ModulePermissions");
Id(u => u.MId).GeneratedBy.Identity();
Map(u => u.Id).Column("ModuleName");
Map(u => u.View);
Map(u => u.Edit);
Map(u => u.Add);
Map(u => u.Delete);
References(x => x.Roles).Column("RolePermissionId");
}
}
public class RoleMapping : ClassMap<Role>
{
public RoleMapping()
{
Table("ModuleRole");
Id(u => u.RId).GeneratedBy.Identity();
Map(u => u.Name);
Map(u => u.Site_Id).Column("SiteId");
Map(u => u.Site_Name).Column("SiteName");
Map(u => u.Domain);
References(x => x.Project).Column("RoleProjectId");
HasMany(u => u.permissions).KeyColumn("RolePermissionId").Inverse().Cascade.All().Not.LazyLoad();
}
}
public class ProjectsMapping : ClassMap<Project>
{
public ProjectsMapping()
{
Table("Projects");
Id(u => u.PId).GeneratedBy.Identity();
Map(u => u.Id).Column("ApiProjectId");
Map(u => u.Name);
HasMany(u => u.Roles).KeyColumn("RoleProjectId").Inverse().Cascade.All().Not.LazyLoad();
}
}

Many to Many Nhibernate - Duplicate records and no insert

I have three tables in a many to many relationship with the nhibernate maps below. My objects are also below. A portfolio item can have many tags. The problem I am having is
1) update save another tag even when the name is the same as last time. So duplicate records get inserted into tag when the tag is the same. So for example if the tag for one portfolio object was abc the next portfolio item that adds the tag should reference this record rather than reinserting abc. I think this is because of the id column in the tag map. Nhibernate needs an id though.
2) Create does not add records in the join table. Records in the join table are only added on updates.
Domain Objects
public class Portfolio {
public Portfolio() {
PortfolioImage = new List<Portfolioimage>();
Tag = new List<Tag>();
}
public virtual int PortfolioId { get; set; }
public virtual string AliasTitle { get; set; }
public virtual string MetaDescription { get; set; }
public virtual string Title { get; set; }
public virtual string Client { get; set; }
public virtual string Summary { get; set; }
public virtual string Url { get; set; }
public virtual string MainImage { get; set; }
public virtual string TitleAlt { get; set; }
public virtual string Description { get; set; }
public virtual IList<Portfolioimage> PortfolioImage { get; set; }
public virtual IList<Tag> Tag { get; set; }
}
public class Portfoliotag {
public virtual int Id { get; set; }
public virtual Portfolio Portfolio { get; set; }
public virtual Tag Tag { get; set; }
}
public class Tag {
public Tag() {
Portfolio = new List<Portfolio>();
}
public virtual int TagId { get; set; }
public virtual string TagVal { get; set; }
public virtual IList<Portfolio> Portfolio { get; set; }
}
Maps
public class PortfolioMap : ClassMap<Portfolio> {
public PortfolioMap() {
Table("Portfolio");
LazyLoad();
Id(x => x.PortfolioId).GeneratedBy.Identity().Column("PortfolioId");
Map(x => x.AliasTitle).Column("AliasTitle").Not.Nullable();
Map(x => x.MetaDescription).Column("MetaDescription").Not.Nullable();
Map(x => x.Title).Column("Title").Not.Nullable();
Map(x => x.Client).Column("Client").Not.Nullable();
Map(x => x.Summary).Column("Summary").Not.Nullable();
Map(x => x.Url).Column("Url");
Map(x => x.MainImage).Column("MainImage");
Map(x => x.TitleAlt).Column("TitleAlt");
Map(x => x.Description).Column("Description").Not.Nullable();
HasMany(x => x.PortfolioImage).KeyColumn("PortfolioId").Inverse();
HasManyToMany(x => x.Tag).Table("PortfolioTag").ParentKeyColumn("PortfolioId").ChildKeyColumn("TagId").LazyLoad().Cascade.All().Fetch.Join();
}
}
public class PortfoliotagMap : ClassMap<Portfoliotag> {
public PortfoliotagMap() {
Table("PortfolioTag");
LazyLoad();
Id(x => x.Id).GeneratedBy.Identity().Column("Id");
References(x => x.Portfolio).Not.Nullable().Cascade.SaveUpdate().Column("PortfolioId");
References(x => x.Tag).Not.Nullable().Cascade.SaveUpdate().Column("TagId");
}
}
public class TagMap : ClassMap<Tag> {
public TagMap() {
Table("Tag");
LazyLoad();
Id(x => x.TagId).GeneratedBy.Identity().Column("TagId");
Map(x => x.TagVal).Column("Tag").Not.Nullable();
//HasMany(x => x.PortfolioTag).KeyColumn("TagId");
// HasMany(x => x.PortfolioTag).Cascade.AllDeleteOrphan().Inverse().Fetch.Join().KeyColumn("TagId");
HasManyToMany(x => x.Portfolio).Table("PortfolioTag").ParentKeyColumn("PortfolioId").ChildKeyColumn("TagId").LazyLoad().Inverse().Cascade.AllDeleteOrphan();
}
}
given the classes
public class Portfolio
{
public Portfolio()
{
Tag = new List<Tag>();
}
public virtual int PortfolioId { get; protected set; }
public virtual IList<Tag> Tag { get; protected set; }
}
public class Tag
{
public virtual int TagId { get; set; }
public virtual string Name { get; set; }
}
the this mapping should suffice
public class PortfolioMap : ClassMap<Portfolio>
{
public PortfolioMap()
{
Id(x => x.PortfolioId).GeneratedBy.Identity().Column("PortfolioId");
HasManyToMany(x => x.Tag)
.Table("PortfolioTag")
.ParentKeyColumn("PortfolioId")
.ChildKeyColumn("TagId")
.Cascade.All()
.Fetch.Join();
}
}
assigning existing tags has to be handled in code which can cache or query involved tags more efficiently than automatic querying by any framework.
Update:
example usage which works for me
public void Save(int portfolioId, IEnumerable<string> tagnames)
{
using (var tx = session.BeginTransaction())
{
var tags = Session.QueryOver<Tag>().WhereProperty(x => x.Name).In(tagnames).List();
var portfolio = session.Get<Portfolio>(portfolioId);
portfolio.Tags.Clear();
portfolio.Tags.AddRange(tags);
tx.Commit();
}
}

Fluent NHibernate: How to map two non-key columns

How would I be able to Map an object inside of another with two columns that arent keys?
public class Car
{
public virtual int Id { get; set; }
public virtual int AccountId { get; set; }
}
public class UserAccount
{
public virtual int Id { get; set; }
public virtual int UserId{ get; set; }
public virtual int AccountId { get; set; }
}
public class User
{
public virtual int Id { get; set; }
public virtual int Name { get; set; }
}
Lets say I wanted to get all Cars with a User.Name of "joe". How would I map / query these with fluent nhibernate?
public Car()
{
Table("Car");
Id(x => x.Id).Column("ID").GeneratedBy.Native();
Map(x => x.AccountId);
References(x => x.Account); // ?? needs to map accountid with the Account.Id...
}
If you want to map a reference, you need the type, not the key.
public class Car
{
public virtual int Id { get; set; }
public virtual UserAccount Account { get; set; }
}
Then you would map it like this
public Car()
{
Table("Car");
Id(x => x.Id).Column("ID").GeneratedBy.Native();
References(x => x.Account, "AccountId");
}

two class reference eachother , how to do Not.LazyLoad in fluent nhibernate

i have two class
public class ProInfo
{
public ProInfo()
{
ProPrices = new List<ProPrice>();
}
public virtual Guid ProID { get; set; }
public virtual string ProCate { get; set; }
public virtual string Name { get; set; }
public virtual string Unit { get; set; }
public virtual string PicName { get; set; }
public virtual string Memo { get; set; }
public virtual bool DeleteFlag { get; set; }
public virtual DateTime LastUpDateTime { get; set; }
public virtual IList<ProPrice> ProPrices { get; set; }
}
public class ProPrice
{
public virtual int Id { get; set; }
public virtual AreaInfo AreaInfo { get; set; }
public virtual ProInfo ProInfo { get; set; }
public virtual Decimal Price { get; set; }
}
mapping codes are :
public ProInfoMap()
{
Id(x => x.ProID);
Map(x => x.DeleteFlag);
Map(x => x.Name);
Map(x => x.PicName);
Map(x => x.ProCate);
Map(x => x.Unit);
Map(x => x.LastUpDateTime);
HasMany<ProPrice>(x => x.ProPrices);
}
public ProPriceMap()
{
Id(x => x.Id);
Map(x => x.Price);
References<ProInfo> (x => x.ProInfo);
References<AreaInfo>(x => x.AreaInfo);
}
what i want is to disable the proprices's lazyload(), so i can get all the prices for the product from database. but, when i change the onetomany to this: HasMany<ProPrice>(x => x.ProPrices).Not.LazyLoad(), it cause an Infinite loop. what do i miss?
I don't know, where exactly the loop comes from, but your bidirectional association may cause this. You should declare one side as Inverse(). This can only be done in ProInfoMap, because it is a one-to-many relationship with a bidirectional association:
HasMany<ProPrice>(x => x.ProPrices).Inverse().Not.LazyLoad();
Try that. It may remove the infinite loop.

How am I supposed to query for a persisted object's property's subproperty in nhibernate?

I'm feeling dumb.
public class Uber
{
public Foo Foo { get; set; }
public Bar Bar { get; set; }
}
public class Foo
{
public string Name { get; set; }
}
...
var ubercharged = session.CreateCriteria(typeof(Uber))
.Add(Expression.Eq("Foo.Name", "somename"))
.UniqueResult<Uber>();
return ubercharged;
This throws a "could not resolve property" error.
What am I doing wrong? I want to query for an Uber object that has a property Foo which has a Name of "somename".
updated with real life example, repository call, using fluent nhibernate:
public UserPersonalization GetUserPersonalization(string username)
{
ISession session = _sessionSource.GetSession();
var personuser = session.CreateCriteria(typeof(UserPersonalization))
.Add(Expression.Eq("User.Username", username))
.UniqueResult<UserPersonalization>();
return personuser;
}
The classes/mappings:
public class User
{
public virtual Guid UserId { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string PasswordSalt { get; set; }
public virtual bool IsLockedOut { get; set; }
public virtual bool IsApproved { get; set; }
}
public class Person
{
public virtual int PersonId { get; set; }
public virtual string Name { get; set; }
public virtual Company Company { get; set; }
}
public class UserPersonalization
{
public virtual int UserPersonalizationId { get; set; }
public virtual Person Person { get; set; }
public virtual User User { get; set; }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.UserId).GeneratedBy.Guid().ColumnName("UserId");
Map(x => x.Username);
Map(x => x.PasswordHash);
Map(x => x.PasswordSalt);
Map(x => x.Email);
Map(x => x.IsApproved);
Map(x => x.IsLockedOut);
}
}
public class UserPersonalizationMap : ClassMap<UserPersonalization>
{
public UserPersonalizationMap()
{
WithTable("UserPersonalization");
Id(x => x.UserPersonalizationId).ColumnName("UserPersonalizationId");
References(x => x.Person).ColumnName("PersonId");
References(x => x.User).ColumnName("UserId");
}
}
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Id(x => x.PersonId).ColumnName("PersonId");
Map(x => x.Name);
References(x => x.Company).ColumnName("CompanyId");
}
}
Try this:
var ubercharged = session.CreateCriteria(typeof(Uber))
.CreateCriteria("Foo")
.Add(Restrictions.Eq("Name", "somename"))
.UniqueResult<Uber>();
Can you sort using "ubercharged.AddOrder(Order.asc("Foo.Name")) syntax? This syntax should work in NHib 2.01. If not, your maps are not working correctly.
Stuart's answer should work fine for you though.