Fluent NHibernate: How to map two non-key columns - nhibernate

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");
}

Related

Fluent NHibernate - 1:1 Relationship with Nullable Field

Given the following model, I want to be able to enter a new WriteOffApprovalUser and have the Employee field be null. This is a 1:1 or null relationship.
public class WriteOffApprovalUser
{
public virtual string UserName { get; set; }
public virtual Employee Employee { get; set; }
}
public class Employee
{
public virtual string EmployeeID { get; set; }
public virtual string EmployeeStatusCode { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string JobTitle { get; set; }
public virtual string Division { get; set; }
public virtual string Department { get; set; }
public virtual string Location { get; set; }
public virtual string City { get; set; }
public virtual string DeskLocation { get; set; }
public virtual string MailID { get; set; }
public virtual string Phone { get; set; }
public virtual string PreferredName { get; set; }
public virtual string Fax { get; set; }
public virtual string SecCode { get; set; }
public virtual string SupervisorID { get; set; }
public virtual string UserId { get; set; }
}
Class Maps
public class WriteOffApprovalUserMap : ClassMap<WriteOffApprovalUser>
{
public WriteOffApprovalUserMap()
{
Table("WRITEOFF_APPROVAL_USER");
Id(x => x.UserName).Column("USER_NAME");
//Map(x => x.Employee).Nullable();
HasOne(x => x.Employee)
.Class<Employee>()
.Constrained()
.Cascade.SaveUpdate()
.PropertyRef("UserId");
}
}
public class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Table("ADP_EMPLOYEE");
Id(x => x.EmployeeID).Column("EMPLID").GeneratedBy.Native("");
Map(x => x.FirstName).Column("FIRST_NAME");
Map(x => x.LastName).Column("LAST_NAME");
Map(x => x.PreferredName).Column("PREFERRED_NAME");
Map(x => x.UserId).Column("USER_ID");
}
}
Query/Save
using (var session = SessionProvider.GetSession())
{
using (var tx = session.BeginTransaction())
{
var user = new WriteOffApprovalUser() { UserName = "SAMSTR" };
session.Save(user);
tx.Commit();
}
}
This complains that Employee is null. How do I specify that Employee can be null?
Also, do all Id fields have to be integral? A lot of the keys on our tables are strings.
First off all if you put it as 1:1 it shouldn't be NULL because it's not correct design.
But here is an example of how to do so:
1) One way
HasOne(x => x.Employee)
.Class<Employee>().Nullable().NotFound.Ignore().PropertyRef("UserId");
2) Second way
References(x => x.Category).Column("UserId").Nullable().NotFound.Ignore();

How to use composite Ids in one-to-many mappings in fluent nhibernate?

I got a scenario where a composite Id uniquely identifies an entity. I defined the MSSQL to have a multiple primary key on those fields. In addition I would like an auto-incremented id to be used for referencing a one-to-many relationship. Here's the schema:
public class Character
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Region Region { get; set; }
public virtual string Realm { get; set; }
public virtual IList<CharProgression> Progression { get; set; }
}
public class CharProgression
{
public virtual int Id { get; set; }
public virtual Character Character { get; set; }
public virtual Stage Stage { get; set; }
public virtual int ProgressionPoints { get; set; }
public virtual int NumOfSaves { get; set; }
}
public class Stage
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
The mappings look like this:
class CharacterMap : ClassMap<Character>
{
public CharacterMap()
{
Table("characters");
Id(ch => ch.Id, "id").GeneratedBy.Identity().Not.Nullable();
CompositeId().KeyProperty(ch => ch.Region, "region")
.KeyProperty(ch => ch.Realm, "realm")
.KeyProperty(ch => ch.Name, "name");
HasMany<CharProgression>(ch => ch.Progression).Inverse().Cascade.All();
}
}
class CharProgressionMap : ClassMap<CharProgression>
{
public CharProgressionMap()
{
Table("char_progression");
CompositeId().KeyReference(cprog => cprog.Character, "char_id",
.KeyReference(cprog => cprog.Stage, "stage_id");
Id(cprog => cprog.Id, "id").GeneratedBy.Identity().Not.Nullable();
Map(cprog => cprog.ProgressionPoints, "progression_points");
Map(cprog => cprog.NumOfSaves, "num_of_saves");
}
}
public class StageMap : ClassMap<Stage>
{
public StageMap()
{
Table("stages");
Id(st => st.Id, "id").GeneratedBy.Identity().Not.Nullable();
Map(st => st.Name, "name");
Map(st => st.Description, "description");
}
}
Now, the thing is that I would like to use SaveOrUpdate() on a character and use the composite id for the update, since the character uniqueness is defined by those 3 fields - region, realm, name.
However, when I am referencing the Character from CharProgression, I don't want to use the composite Id as I don't want the char_progression table to hold 3 fields for identifying a character, a simple Id is enough... which is why I also defined an IDENTITY id on the Character entity.
Is what i'm trying possible? or is there another way to achieve this?
Thanks :)

Illegal access to loading collection in Fluent and Nhibernate

I'm not able to understand why the problem is occurring. Please let me know if there are any errors, I am very new to this topic.
public class Department
{
public virtual int Dept_id { get; set; }
public virtual String Dept_name { get; set; }
public virtual IList<Student> Students { get; set; }
//public virtual ICollection<Student> Students { get; set; }
public Department()
{
Students = new List<Student>();
}
}
public class Student
{
public Student()
{
}
//private int _Dept_id;
//public virtual Guid StudentId { get; set; }
public virtual Guid StudentId { get; set; }
/*public virtual int Dept_id
{
get { return this._Dept_id; }
set { this._Dept_id = value; }
}*/
public virtual int Dept_id { get; set; }
public virtual String Name { get; set; }
public virtual int Age { get; set; }
public virtual String Address { get; set; }
public virtual Department Department { get; set; }
}
public class DepartmentMap : ClassMap<Department>
{
public DepartmentMap()
{
Table("Department");
Id(x => x.Dept_id).Column("Dept_id");
Map(x => x.Dept_name).Column("Dept_name");
HasMany(x => x.Students).KeyColumn("Student_id").Inverse()
.Cascade.All();
}
}
public class StudentMap :ClassMap<Student>
{
public StudentMap()
{
Table("Student");
Id(x => x.StudentId).Column("Student_id").GeneratedBy.GuidComb();
Map(x => x.Name);
Map(x => x.Age);
Map(x => x.Address);
References(x => x.Department).Column("Dept_id")
.Not.Nullable().Not.LazyLoad();
}
}
Now when I am trying this code
[WebMethod(EnableSession = true)]
public List<Student> Students()
{
IList<Student> student = new List<Student>();
ISession session = NHibernateHelper.OpenSession();
student = session.Query<Student>().ToList();
return student.ToList();
}
it gives error in loading the students list inside the department as
illegal access to loading collection
What is lacking in this code and why this is happening?
sorry my bad !! there are cetain changes i made which made it working .. though not sure of apparent shortcomings of the mentioned idea below
changed student class as :
public class Student
{
public Student()
{
}
public virtual Guid StudentId { get; set; }
public virtual int Dept_id
{
get { return Department.Dept_id; }
set { this.Dept_id = Department.Dept_id; }
}
public virtual String Name { get; set; }
public virtual int Age { get; set; }
public virtual String Address { get; set; }
public virtual Department Department { get; set; }
}
and student mapping for the reference as
References(x => x.Department).Column("Dept_id").Cascade.All();
Note : there should be no single Dept Id mapping
and changed the DepartmentMap as :
public DepartmentMap()
{
Table("Department");
Id(x => x.Dept_id).Column("Dept_id");
Map(x => x.Dept_name).Column("Dept_name");
HasMany(x => x.Students).KeyColumn("Dept_id").AsBag();
}

Nhibernate Mapping relationships on multiple columns

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");
}
}

Fluent NHibernate HasMany in Component

Below is a class model and an Oracle schema that I would like to map it to using Fluent NHibernate.
public enum EnumA { Type1, Type2, Type3 };
public class ClassB
{
public virtual string Property1 { get; set; }
public virtual string Property2 { get; set; }
}
public class ClassA
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual IDictionary<EnumA, IList<ClassB>> MyDictionary { get; set; }
}
TableA (NUMBER(38) ID PK, VARCHAR2(255) Name)
TableB (NUMBER(38) ID PK FK, NUMBER(38) Type PK, VARCHAR(255) Prop1, VARCHAR(255) Prop2)
How should I define the Fluent NHibernate mapping class?
I don't mind introducing a new domain class if necessary. I have tried the following:
public class ClassB
{
public virtual string Property1 { get; set; }
public virtual string Property2 { get; set; }
}
public class classC
{
public virtual EnumA EnumA { get; set; }
IList<ClassB> ClassBList { get; set; }
}
public class ClassA
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual IDictionary<EnumA, classC> MyDictionary { get; set; }
}
with the following mapping class
public ClassAMap()
{
WithTable("ClassA");
Id(x => x.ID);
Map(x => x.Name);
HasMany(x => x.MyDictionary).AsMap<EnumA>(d => d.EnumA).Component(c =>
{
c.HasMany(e => e.ClassBList).Component(f =>
{
f.Map(x => x.Property1);
f.Map(x => x.Property1);
});
});
}
However, this does not generate a valid configuration. Can anybody help?
Class B isn't a component of A, it's a related entity with its own identity (ID, Type) so it can't logically be a component, as components don't have their own identity (PK) otherwise they would be separate entities.