In Criteria I do SetFetchMode as Lazy but still fetching all items, how can I fix this?
public class MenuItem : BaseClass<MenuItem>
{
public virtual int MenuItemId { get; set; }
public virtual string Text { get; set; }
public virtual IList<MenuItem> Children { get; set; }
public virtual MenuItem Parent { get; set; }
public MenuItem()
{
Children = new List<MenuItem>();
}
}
class MenuItemMap : ClassMap<MenuItem>
{
public MenuItemMap()
{
Id(x => x.MenuItemId);
Map(x => x.Text);
HasMany(x => x.Children).KeyColumn("ParentId").Not.LazyLoad().Fetch.Select();
References(x => x.Parent).Not.LazyLoad().Fetch.Select();
}
}
using (var session = NHibernateHelper<T>.OpenSession())
{
var CC = session.CreateCriteria(typeof(T));
CC.SetFetchMode("Children", FetchMode.Lazy);
return CC.List<T>();
}
I have to say, that this is not possible. Our JAVA brother Hibernate (from which NHibernate was ported into .NET) seems to have that option:
Hibernate: Enabling lazy fetching in Criteria API
But NHibernate does not support that. Chek also Override lazy loading behavior 'lazy=false'.
What we can do, is to bet on Projections. This way we really assemble exactly one SQL statement and get a list of Transformed objects (semi-filled, dependent on amount of selected properties)
16.6. Projections
Here is an example how to build a deep projections (including References/many-to-one)
Here is how to transform them into originally mapped object Graph.
Related
I am trying to update an nHibernate object with a child collection using the .Update() method found on a hibernate session. The only thing that I can do with the current setup is add children, I can not modify them or remove them.
For clarification the objects and their mapping are as follows:
public class Parent {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ISet<Child> Children { get; set; } = new HashSet<Child>();
}
public class ParentMap: ClassMap<Parent>
{
public ParentMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Children)
.AsSet()
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
public class Child {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Parent Parent { get; set; }
}
public class ChildMap: ClassMap<Child>
{
public ChildMap()
{
Id(x => x.Id);
Map(x => x.Name);
References(x => x.Parent);
}
}
When I get changes from my UI layer and try to update the already existing object using:
using (var tx = _session.BeginTransaction())
_session.Update(newParent);
tx.Commit();
}
Here newParent is a transient object (obtained from the database in an earlier session andd shown in the UI) containing the same identifier as the object I would like to update, but with changes to the child collection. Somehow using this approach I can only add children, but not modify or remove them.
Where is my mistake?
Most likely what is happening to you, is that instead of modifying the set that NHibernate has instantiated in your Parent entity, you are replacing it all together by a new instance of HashSet.
When you save or get an entity from NHibernate, your Children ISet gets loaded with an instance of a PersistentGenericSet (that implements ISet) which has the responsibility of helping with this change tracking for your collection.
In short, do not assign to the Children property. In fact, make the setter protected.
Just Add() or Remove() or Clear() it as required.
I have Entity Framework set up and it works fine most of the time I need it. I have a structure like so
public partial class Topic : Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
public virtual Post LastPost { get; set; }
public virtual Category Category { get; set; }
public virtual IList<Post> Posts { get; set; }
public virtual IList<TopicTag> Tags { get; set; }
public virtual MembershipUser User { get; set; }
public virtual IList<TopicNotification> TopicNotifications { get; set; }
public virtual IList<Favourite> Favourites { get; set; }
public virtual Poll Poll { get; set; }
}
As you can see I have a number of related entities which are lists. These are mapped as standard and are lazy loaded so I can call Topic.Posts or Topic.TopicNotifications etc... (Mappings below)
HasOptional(t => t.LastPost).WithOptionalDependent().Map(m => m.MapKey("Post_Id"));
HasOptional(t => t.Poll).WithOptionalDependent().Map(m => m.MapKey("Poll_Id"));
HasRequired(t => t.Category).WithMany(t => t.Topics).Map(m => m.MapKey("Category_Id"));
HasRequired(t => t.User).WithMany(t => t.Topics).Map(m => m.MapKey("MembershipUser_Id"));
HasMany(x => x.Posts).WithRequired(x => x.Topic).Map(x => x.MapKey("Topic_Id")).WillCascadeOnDelete();
HasMany(x => x.TopicNotifications).WithRequired(x => x.Topic).Map(x => x.MapKey("Topic_Id")).WillCascadeOnDelete();
HasMany(t => t.Tags)
.WithMany(t => t.Topics)
.Map(m =>
{
m.ToTable("Topic_Tag");
m.MapLeftKey("TopicTag_Id");
m.MapRightKey("Topic_Id");
});
This is all an well. But on a couple of occasions I have the need to manually populate Topic.Posts and Topic.Favorites.
But if I try and set Topic.Posts = SomeCollection it triggers the lazy load and loads all the posts first, and then lets me set my collection so I get two sets of sql executed (The first I don't want)
Is there anyway, to switch off the lazy loading manually on demand for just when I want to set the collection manually?
Hope that makes sense... :/
You would be better to turn off lazy loading by default and instead specify when you want to load the extra data in the first place. EF is set up to allow Eager loading by using the .Include() function on your query, with lazy loading it can get messy if you start turning it on/off for various functions, you're better to just turn it off and manage what/when you want data loaded if you're feeling a need to turn it off.
See https://msdn.microsoft.com/en-nz/data/jj574232.aspx for specific examples and a breakdown of the different ways you can eager/lazy load data. The first example shows how you could pull through posts off a blog, which is similar to what you are wanting to acheive.
var topics = context.Topics
.Include(t => t.Posts)
.ToList();
I am not aware of an approach targeted to this exact scenario so I'd have to go with a temporary disable/enable of lazy loading.
using(var context = new MyContext())
{
context.Configuration.LazyLoadingEnabled = false;
// do your thing using .Include() or .Load()
context.Configuration.LazyLoadingEnabled = true;
}
Note however that this is a global configuration so there might be a concurrency problem if that happens in your scenario.
I would not recommend turning off lazing loading on a per request basis. As AllMadHare suggests, you could turn off lazy loading entirely, but that could force changes to how you load all data. I would recommend removing the virtual keyword from Posts so that your class looks like this:
public partial class Topic : Entity
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime CreateDate { get; set; }
public virtual Post LastPost { get; set; }
public virtual Category Category { get; set; }
public IList<Post> Posts { get; set; }
public virtual IList<TopicTag> Tags { get; set; }
public virtual MembershipUser User { get; set; }
public virtual IList<TopicNotification> TopicNotifications { get; set; }
public virtual IList<Favourite> Favourites { get; set; }
public virtual Poll Poll { get; set; }
}
Per the documentation found here: https://msdn.microsoft.com/en-us/data/jj574232.aspx#lazyOffProperty this will allow you to lazy load all other navigation properties and eager load posts if you need to.
Since you are using lazy loading, you must have proxies generated for your classes and collection properties.
Replacing these proxy collection properties with your own collections seems pretty weird design to me. You loose change tracking and most probably gain a couple of other strange side effects.
I would recommend to either use proxies/lazy loading and give up the idea of replacing the collections, or stand back from using proxies and gain full control on the generated POCO classes.
Which of both approaches suits best for your needs depends on your overall usage of the entity framework.
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>();
I have a simple many-to-many relationship using Fluent NHibernate and it is working pretty fine.
Here is my first class mapping:
public LobMapping()
{
...
HasManyToMany(x => x.Commodities)
.Table("PPBSYS.LOB_COMMODITY")
.ParentKeyColumn("LOB_ID")
.ChildKeyColumn("COMMODITY_ID")
.Cascade.SaveUpdate()
.LazyLoad();
...
}
Here is my second class mapping:
public CommodityMapping()
{
...
HasManyToMany(x => x.Lobs)
.Table("PPBSYS.LOB_COMMODITY")
.ParentKeyColumn("COMMODITY_ID")
.ChildKeyColumn("LOB_ID")
.Inverse()
.Cascade.All()
.LazyLoad();
...
}
And finally, my Lob object has a list of commodities:
public class Lob
{
...
public virtual IEnumerable<Commodity> Commodities { get; set; }
...
}
However I am not happy with the fact that I must reference the entire commodity inside the Lob class. I really would like to do:
var lob = new Lob();
lob.Commodities = new [] { new Commodity { CommodityId = 1 }};
repository.SaveLob(lob);
But if I run the code above, NHibernate will try to update the Commodity table setting the columns to null for the commodity with ID = 1.
So actually I must get the entire object, before saving the Lob:
var lob = new Lob();
lob.Commodities = new [] { repostitory.GetCommodit(1) };
repository.SaveLob(lob);
And I know that the commodity exists, because the user just have selected them.
It is possible to accomplish my task?
I assume your repository is calling session.Get<T>(id) under the covers. There is also session.Load<T>(id).
lob.Commodities = new [] { session.Load<Commodity>(1) };
From the NHibernate documentation on Load()...
If the class is mapped with a proxy, Load() returns an object that is an uninitialized proxy and does not actually hit the database until you invoke a method of the object. This behaviour is very useful if you wish to create an association to an object without actually loading it from the database.
Daniel's answer sounds promising, let me know if in Save the proxy won't hit the database to fill all the properties of the entity.
Another answer would be a little forcefully on Nhibernate, i tested it and it's working,
working code :
public class Com
{
public virtual Guid ID { get; set; }
public virtual string Name { get; set; }
public virtual IList<Lob> Lobs { get; set; }
}
public class Lob
{
public virtual Guid ID { get; set; }
public virtual string Name { get; set; }
public virtual IList<Com> Coms { get; set; }
}
class LobMap : ClassMap<Lob>
{
public LobMap()
{
Id(x => x.ID).GeneratedBy.GuidComb();
Map(x => x.Name);
HasManyToMany(x => x.Coms)
.Table("LOB_COM")
.ParentKeyColumn("LOB_ID")
.ChildKeyColumn("COM_ID")
.Cascade.SaveUpdate()
.LazyLoad();
}
}
class ComMap : ClassMap<Com>
{
public ComMap()
{
Id(x => x.ID).GeneratedBy.GuidComb();
Map(x => x.Name);
HasManyToMany(x => x.Lobs)
.Table("LOB_COM")
.ParentKeyColumn("COM_ID")
.ChildKeyColumn("LOB_ID")
.Inverse()
.Cascade.All()
.LazyLoad();
}
}
Now - I set a dummy entity to mimic the connection table and map it :
public class ComLobConnection
{
public virtual Guid ComID { get; set; }
public virtual Guid LobID { get; set; }
}
public class ComLobConnectionMap : ClassMap<ComLobConnection>
{
public ComLobConnectionMap()
{
Table("LOB_COM");
Id();
Map(x => x.ComID,"COM_ID");
Map(x => x.LobID,"LOB_ID");
}
}
Notice that i'm mapping to exact same fields and Table as the ManyToMany, with no ID set up (that's the empty Id() call)
Now all that's left is to save a ComLobConnection and it will be added to the Com.Lobs and Lob.Coms
Saved some test Com,Lob
var testCom = new Com() { Name = "TestCom" };
var testLob = new Lob() { Name = "TestLob" };
session.SaveOrUpdate(testCom);
session.SaveOrUpdate(testLob);
after save - took their ID's and saved a connection to test
var testConnection = new ComLobConnection()
{
ComID = Guid.Parse("D3559F53-8871-45E9-901D-A22800806567"),
LobID = Guid.Parse("D372D430-2E61-44F2-BA89-A228008065F1")
};
session.SaveOrUpdate(testConnection);
This forced a new record in the manytomany table, and worked when getting both Lob and Com after.
I'm not recommending this :), It just interested me if it can be done, and it can.
This way you will not hit the DB for loading Coms or Lobs that you know exist to save their connection.
Hopefully Load() will not hit the DB for that too :)
Edit : can be done with any kind of ID
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?