In my code I have an three main entities:
1. Company
2. Staff
3. Position
A staff can have several positions in various companies.
I want to retrieve all staff associated to a specific company.
In code I would do something like:
public partial class Company
{
public virtual IEnumerable<Position> Positions { get; protected set; }
public virtual IEnumerable<Staff> Staffs
{
get { return Positions.Select(x => x.Staff); }
}
}
class CompanyMap : ClassMap<Company>
{
public CompanyMap()
{
Id(x => x.Id)
.Column("CompanyId")
.GeneratedBy.Identity();
Map(x => x.Name)
.Not.Nullable();
HasMany(x => x.Positions)
.KeyColumn("CompanyId")
.AsBag();
}
}
Pb: In this solutionm I will load all positions associated to a company and then all staff associated to each position... In terms of performance it's not very good i guess...
I'm pretty sure there is a better way to perform this join directly in the CompanyMap class.
Could you help me to do that?
Thank you,
Sebastien
How about altering data model ? It seems that Staff is always in a given Position collection at the given Company level. This suggest following model
public partial class Staff
{
public virtual IEnumerable<CompanyPosition> Positions { get; protected set; }
}
public class Position
{
//...
}
public class Company
{
//...
}
public class CompanyPosition
{
public virtual Company Company {get;set;}
public virtual IEnumerable<Position> {get;set;}
}
With this you can do straightforward mapping and your query ends up similar to this
var data = session.Query<Staff>().Where(s=>s.CompanyPosition.Company == company);
Related
I have following model
public class Car : Entity<int>
{
public virtual int Id{ get; set; }
...
public virtual Engine Engine { get; set; }
}
and I'm using nhibernate mapping by code approach
public class CarMap : ClassMapping<Car>
{
public CarMap()
{
Id(x => CarId, m => m.Generator(Generators.Identity));
// how map reference Engine?
**// edit**
HasOne(x=>x.Engine, m=>{}) // is this good enough?
}
}
how map Engine in this CarMap object?
You need a little more information in the question, but here's a couple of options.
Is this really a one to one relationship? One to one relationships are somewhat unique in that both sides of the relationship tend to share the same Id. Like David Osborne said you most likely want a One to Many relationship. But you you want it to be bi-directional? i.e. you can navigate down from the Engine to all the cars that may have that engine or up from the car to a specific engine. i.e. engine is Chrysler Hemi engine 5.7L and it is in the cars, Ram Pickup, Dodge Durango, Dodge Charger.
Then you may want to map the objects like this
public class Engine : Entity<int>
{
public Engine()
{
Cars = new List<Car>();
}
public virtual int Id { get; protected set; }
public virtual decimal Displacement { get; set; }
//more properties
public virtual IList<Car> Cars { get; }
public virtual void AddCar(Car car)
{
if (Cars.Contains(car)) return;
Cars.Add(car);
}
public virtual void RemoveCar(Car car)
{
if (!Cars.Contains(car)) return;
Cars.Remove(car);
}
}
public class Car : Entity<int>
{
public virtual int Id { get; set; }
public virtual Engine Engine { get; set; }
}
So if you are mapping the Engine you need to define the Cars mapping list this
Bag(x => x.Cars, map =>
{
map.Key(k => k.Column(col => col.Name("EngineId")));
map.Cascade(Cascade.All | Cascade.DeleteOrphans); //optional
},
action => action.OneToMany());
and the other side of the relationship like this
ManyToOne(x => x.Engine, map =>
{
map.Column("EngineId");
map.NotNullable(true); // if you require the Engine to be in a car
});
If you just want a one way mapping from the car to the engine, just remove all the references to the Cars list and delete the Bag mapping.
Using Fluent NH, I would use References(), which has a mapping-by-code equivalent of ManyToOne() apparently.
I have following tables
Car(CarId, Name,...)
CarPartLink(CarId, PartId)
Part(PartId, Name)
SubPartLink(Parent_PartId, Child_PartId) where both parent and child comes from Part table
I want Car object to have list of Parts including the SubParts, here Car does not have direct relationship with Part its Subparts and neither Part has a direct relation with Subparts.
i.e.
class Car
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<Parts> AllParts { get; set; } //This should include all the parts and its subparts assuming subparts are only one level deep
}
How to make the map for the same in Fluent NHibernate?
Edit 1:
If it is not possible in Fluent NHibernate but possible in NHibernate mapping then also fine with me.
I am using Fluent NHibernate version: 1.4.0.1 and NHibernate version: 3.3.3
Edit 2:
I am also fine if I get only the subparts, or the id's of subparts in the map.
Edit 3:
Each vehicle( here in the example mentioned as Car) has more than 1 million parts and subparts combined, out of which user would be actually be using few 100 parts depending on the conditions. e.g. Get all parts that are weighing 100 kg or get all parts that are of type "Screw" etc. I will be needing these data in read only mode.
There is already a fine tutorial on relationship mappings in the FluentNH wiki. I suggest you read the guide, or even better, follow it step-by-step. Assuming the following entities:
public class Car
{
public virtual int CarId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Part> AllParts {get; set;}
public Car()
{
AllParts = new List<Part>();
}
}
public class Part
{
public virtual int PartId { get; set; }
public virtual string Name { get; set; }
public virtual IList<Car> AllCars {get; set;}
//never tried mapping a many-to-many on the same entity, but this should work...
public virtual IList<Part> ParentParts {get; set;}
public virtual IList<Part> SubParts {get; set;}
public Part()
{
AllCars = new List<Car>();
ParentParts = new List<Part>();
SubParts = new List<Part>();
}
}
Your mapping will probably be something like this:
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(x => x.CarId);
Map(x => x.Name);
HasManyToMany(x => x.AllParts)
//depending on your logic, you would either set .Inverse here or in the PartMap
.Table("CarPartLink")
.ParentKeyColumn("CarId")
.ChildKeyColumn("PartId")
.Cascade.All();
}
}
public class PartMap : ClassMap<Part>
{
public PartMap()
{
Id(x => x.PartId);
Map(x => x.Name);
HasManyToMany(x => x.AllCars)
.Table("CarPartLink")
.ParentKeyColumn("PartId")
.ChildKeyColumn("CarId")
.Cascade.All();
HasManyToMany(x => x.ParentParts)
.Table("SubPartLink")
.ParentKeyColumn("Parent_PartId")
.ChildKeyColumn("Child_PartId")
.Inverse() //saving done from the child side of the relationship, right?
.Cascade.All();
HasManyToMany(x => x.SubParts)
.Table("SubPartLink")
.ParentKeyColumn("Child_PartId")
.ChildKeyColumn("Parent_PartId")
.Cascade.All();
}
}
If the above doesn't work, let me know. Apparently there is a bug in some versions of FNH where you will need to employ a special workaround. You can find the workaround in this question (look for self-submitted answer by the OP), which is based on the same scenario as yours (many-many on the same entity).
EDIT: If you want to obtain all the parts and subparts for a Car, you will need to recursively access the SubParts for every single Part in your Car.AllParts collection.
Car Car1 = new Car();
//code to get car object
IList<Part> AllParts = new List<Part>();
GetAllParts(Car.AllParts, ref AllParts); //call a recursive method to add all the parts and subparts to the list
//do something with the list
public void GetAllParts(IList<Part> parentList, ref IList<Part> partsList)
{
foreach (Part part in parentList)
{
if (!partsList.Contains(part)) //validate if the list already contains the part to prevent replication
partsList.Add(part); //add this part to the list
if (part.SubParts.Count > 0) //if this part has subparts
GetSubParts(part.SubParts, ref partsList); //add all the subparts of this part to the list too
}
}
Edit2: This blog post seems to be exactly what you need...
session.CreateQuery(
"select parts from Car as car " +
"join car.AllParts as parts join fetch parts.SubParts where ...")
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.List<Employee>();
Is there a way I can setup mapping for a table that doesn't have a direct reference to another table? It actually gets it's reference from another table that I do have a direct reference from.
This is what I have so far, but I'm not sure how to map the "LookupValue" in my MetaData model. It would need to map to MetaData if the [mdd].DefinitionType equals the [mdl].LookupType and the [md].DataValue equals the [mdl].LookupKey.
public class MetaData {
public virtual long TableID { get; set; }
public virtual MetaDataDefinition Definition { get; set; }
public virtual int DefinitionID { get; set; }
public virtual String DataValue { get; set; }
public virtual MetaDataLookup LookupValue { get; set; }
public override bool Equals(object obj) { ... }
public over int GetHashCode() { ... }
}
public class MetaDataDefinition {
public virtual long ID { get; set; }
public virtual string DefinitionName { get; set; }
public virtual string DefinitionType { get; set; }
}
public class MetaDataLookup {
public virtual string Type { get; set; }
public virtual string LookupKey { get; set; }
public virtual string LookupValue { get; set; }
public override bool Equals(object obj) { ... }
public over int GetHashCode() { ... }
}
public class MetaDataMap : ClassMap<MetaData> {
public MetaDataMap() {
Table("PPOMetaData");
CompositeId()
.KeyProperty(x => x.TableID, "TableID")
.KeyProperty(x => x.DefinitionID, "DefinitionID");
References(x => x.Defintion, "DefinitionID").Not.LazyLoad().Cascade.All().Fetch.Join();
Map(x => x.TableID);
Map(x => x.DataValue);
}
}
public class MetaDataDefinitionMap : ClassMap<MetaDataDefinition> {
public MetaDataDefinitionMap() {
Table("MetaDataDefinitions");
Id(x => x.ID);
Map(x => x.DefinitionName);
Map(x => x.Type);
}
}
public class MetaDataLookupMap : ClassMap<MetaDataLookup> {
public MetaDataLookupMap() {
CompositeId()
.KeyProperty(x => x.LookupType)
.KeyProperty(x => x.LookupKey);
Map(x => x.LookupValue);
}
}
Ideally, I want to have it run a query similar to this:
SELECT data.TableID, data.DefinitionID, def.DefinitionName, data.DataValue,lu.LookupValue AS DataValue
FROM dbo.PPOMetadata AS data
INNER JOIN dbo.MetaDataDefinitions AS def ON def.ID = data.DefinitionID
LEFT OUTER JOIN dbo.MetaDataLookup AS lu ON lu.LookupType = def.Type AND lu.LookupKey = data.DataValue
WHERE data.TableID = 1
In terms of update ability, the only thing I would ever create, update or delete would be in the MetaData table. The definitions and Lookup values would never change (at least from this part of the application). Is mapping the "MetaDataLookup" directly to the MetaData model possible? If so, can someone point me in the right direction of what I should be looking at?
Thanks!
I came up with a workaround that seems to be working and might take some of the complexity out. Instead of trying to handle the complex joins in a ClassMap, I built a view in Sql Server that does this for me. In my application, I built a new Model and ClassMap for the view. I haven't implemented any update logic yet, but I think I'll have the update logic work directly on the MetaData model, while the read logic (which needs everything joined together) will use the new MetaDataView model.
I'm still curious if complex joins like this are possible in Fluent NHibernate, but for now this solution seems to be working for me.
I have the following entities
public abstract class Card
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual Product Product { get; set; }
public virtual Sprint Sprint { get; set; }
}
public class Story:Card
{
public virtual double Points { get; set; }
public virtual int Priority { get; set; }
}
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Story> Stories { get; private set; }
public Product()
{
Stories = new List<Story>();
}
}
And the following mappings
public class CardMap:ClassMap<Card>
{
public CardMap()
{
Id(c => c.Id)
.Index("Card_Id");
Map(c => c.Name)
.Length(50)
.Not.Nullable();
Map(c => c.Description)
.Length(1024)
.Not.Nullable();
References(c=>c.Product)
.Not.Nullable();
References(c=>c.Sprint)
.Nullable();
}
}
public class StoryMap : SubclassMap<Story>
{
public StoryMap()
{
Map(s => s.Points);
Map(s => s.Priority);
}
}
public class ProductMap:ClassMap<Product>
{
public ProductMap()
{
Id(p => p.Id)
.Index("Product_Id");
Map(p => p.Name)
.Length(50)
.Not.Nullable();
HasMany(p => p.Stories)
.Inverse();
}
When I generate my Schema, the tables are created as follows
Card
---------
Id
Name
Description
Product_id
Sprint_id
Story
------------
Card_id
Points
Priority
Product_id
Sprint_id
What I would have expected would have been to see the columns Product_id and Sprint_id ONLY in the Card table, not the Story table.
What am I doing wrong or misunderstanding?
NB: Tested on the NH2 project only
Well, you are probably going to want to chew on a door once you read this, but the TLDR reason is because the Product_id and Spring_id columns in your Story table are not redundant - they exist for the HasMany(x => x.Stories) relations in your SpringMap and ProductMap. They just happen to be share the same naming convention as the CardMap References(x => x.Product and References(x => x.Sprint).
Validate this for yourself by commenting out ProductMap.cs:24-25 and SprintMap.cs:22 and rebuilding.
If the above does not make sense, let me know and I will try to explain in further detail.
So, it should work fine as is. If you want to clarify the columns, you could explicitly define the column names like so:
ProductMap.cs
HasMany(p => p.Stories)
.KeyColumn("ProductOwner_id")
.Inverse();
SprintMap.cs
HasMany(s => s.Stories)
.KeyColumn("SprintOwner_id")
;
CardMap.cs
References(c=>c.Product)
.Column("Product_id")
.Not.Nullable();
References(c=>c.Sprint)
.Column("Sprint_id")
.Nullable();
Here I am guessing that the 1:N relationships between a Story and a Product/Sprint are an "owner". You would want to rename it to whatever is appropriate semantically.
One other thing. I would have thought the last changes (the changes to CardMap.cs) would be unnecessary - but they seem to be for some reason, or the Sprint_id column becomes SprintOwner_id. I have no idea why this would happen - I would speculate that this is some sort of bidirectional relationship inferencing on fluent/nhibernates part gone awry, but I'd put very little money on that.
I see that the Story entity inherits from the Card entity you created, but you don't know why you have Product_Id and Sprint_Id properties in the Story table Schema, since they're virtual properties in the Card class.
I'm guessing that this happens because in NHibernate, all properties need to be virtual but only at first. They don't really stay virtual. The NHibernate framework overrides them, and probably because of this, this is happening to you.
I have created 3 tables in my database and put data into them. The 3 tables all have foreign keys joining them together. Below are the table classes and there mappings. When I run the query listed at the end I get IList<> of the objects and they have the data from all 3 tables. However, my HQL query is only from the top most table. How can I get back just the results from the top most table?
These are my classes:
public class Technology
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual int SortOrder { get; set; }
public virtual string Abbreviation { get; set; }
public virtual IList<TechnologyDescription> TechnologyDescriptions { get; private set; }
public Technology()
{
TechnologyDescriptions = new List<TechnologyDescription>();
}
public virtual void AddTechnologyDescription(TechnologyDescription technologyDescription)
{
technologyDescription.Technology = this;
TechnologyDescriptions.Add(technologyDescription);
}
}
public class TechnologyDescription
{
public virtual int Id { get; private set; }
public virtual Technology Technology { get; set; }
public virtual string Description { get; set; }
public virtual DescriptionType DescriptionType { get; set; }
}
public class DescriptionType
{
public virtual int Id {get; private set;}
public virtual string Type { get; set; }
}
These are my mapping objects:
public class TechnologyMap : ClassMap<Technology>
{
public TechnologyMap()
{
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.SortOrder);
Map(x => x.Abbreviation);
HasMany(x => x.TechnologyDescriptions)
.Inverse()
.Cascade.All();
}
}
public class TechnologyDescriptionMap : ClassMap<TechnologyDescription>
{
public TechnologyDescriptionMap()
{
Id(x => x.Id);
References(x => x.Technology);
Map(x => x.Description);
References(x => x.DescriptionType);
}
}
public class DescriptionTypeMap : ClassMap<DescriptionType>
{
public DescriptionTypeMap()
{
Id(x => x.Id);
Map(x => x.Type);
}
}
And this is my HQL code:
IQuery q = session.CreateQuery("from Technology T");
IList technologies = q.List();
I don't know if it is possible using HQL, but using NHibernate's Criteria API, you can do this:
ICriteria criteria = session.CreateCriteria (typeof(Technology));
criteria.SetFetchMode ("TechnologyDescriptions", FetchMode.Lazy);
var list = criteria.List<Technology>();
However, this is probably not really what you want. The TechnologyDescriptions won't be fetched right now, but they will be fetched once you access them (that is: the first time you call the TechnologyDescriptions property).
When working with NHibernate, you shouldn't think in terms of 'data'. Rather, you should think in terms of 'entities'.
When retrieving an entity, you want to retrieve the entity entirly (directly, or in a lazy fashion). It is not possible to retrieve an entity partially, and this is quite obvious;
What should NHibernate do with an entity that you've retrieved partially, when you try to save that entity ?
Something else that pops in my mind:
I suppose you want to retrieve the Technologies, and nothing related because you want to display them in an overview or something like that ?
In such case, you should take a look at 'Transformations'.
You could for instance create an additional class which is called TechnologyView, which looks like this:
public class TechnologyView
{
public int Id
{
get;
private set;
}
public string Name
{
get;
private set;
}
public string Abbreviation
{
get;
private set;
}
private TechnologyView()
{
// Private constructor, required for NH
}
public TechnologyView( int id, string name, string abbreviation )
{
this.Id = id;
this.Name = name;
this.Abbreviation = abbreviation;
}
}
Once you've done this, you must inform NHibernate about the existance of this class.
You do this by Importing the class in an hbm.xml file for instance . (I do not know how to do it using Fluent).
<import class="MyNamespace.TechnologyView" />
After that, you can create a query (using HQL or Criteria) which retrieves TechnologyView instances. NHibernate is smart enough to generate a performant SQL query.
using HQL:
IQuery q = s.CreateQuery ("select new TechnologyView (t.Id, t.Name, t.Abbreviation) from Technology t");
using Criteria:
ICriteria criteria = s.CreateCriteria (typeof(Technology));
criteria.SetResultTransformer (Transformers.AliasToBean (typeof(TechnologyView));
var result = criteria.List<TechnologyView>();
I think what you're looking for is for the TechnologyDescriptions to be lazy loaded. That way the descriptions get loaded from the database only when they are accessed (NHibernate will issue a second db query. Note that this can lead to N+1 selects in some situations and you might prefer the all at once query depending on the usage.)
By NHibernate xml mappings default to lazy loading of collections. In the past it seems that the Fluent NHibernate did not have the same default. You need to add .LazyLoad() to the mapping.
Recently it looks like lazy loading has become the default fluent mapping:
Is the default behavior with Fluent NHibernate to lazy load HasMany<T> collections?