c#,nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
To map pairing table, without explicit Entity representing it, we have to use <many-to-many>. Also attribute table="..." must be present - to instruct NHibernate about that pairing table. (In case, that we assign Tags into Posts, we should not mark such mapping as inverse) <bag name="Tags" table="t_post_tag" lazy="true" cascade="none" inverse="true">...
java,sql,hibernate,nhibernate,hql
Ok I figured it out. This worked from School s order by size(s.students) As per the Hibernate documentation You can test the size of a collection with the special property size or the special size() function. ...
nhibernate,criteria,criteria-api,queryover,nhibernate-queryover
We cannot override mapping in this case. We can do it opposite way - have lazy in place - and use eager fetching for querying. The decision process (of reference loading) is done outside of the query, ex post. So it could be pre-loaded, but cannot be avoided. Solution here...
The equivalent to the first line, in lambda form is ICriterion cr = Restrictions.Where<Foo>(k => k.Name == "Foo" && (k.Age > 21 || k.HasCar)); ...
In general, we can use configuration setting for updating our DB schema whenever ISessionFactory is created: <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="hbm2ddl.auto">Update</property> Check Table 3.2. NHibernate Configuration Properties We can do it even in our own code: How to update database table schemas with NHibernate schema generation? (snippet from Q &...
So here's what should work (I've greatly simplified the query, but the problems are all the same): IType decimalType = TypeFactory.Basic("decimal(20,2)"); IProjection castProjection = Projections.Cast( decimalType, Projections.Property<DepositAccount>(acct => acct.DepositAccountBalance)); var accounts = session.QueryOver<DepositAccount>() .Where(Restrictions.Eq(castProjection, 1.01)) .List<DepositAccount>(); Unfortunately this generates the following SQL: SELECT this_.* FROM DepositAccount this_ WHERE cast(...
There was code error Instead of cCase.Address = new CaseAddress(); cCase.Address.Street = record.ResidenceStreet; It should have been just cCase.Address.Street = record.ResidenceStreet; cCase.Address = new CaseAddress() was creating a new object for CaseAddress result in new entry. Also the update method should be session.Merge instead of update public bool Update(T persistableEntity)...
Yes you can, something like: // The new Tuple<Foo, Bar>(foo, bar) constructor Type constructor = typeof(Tuple<Foo, Bar>).GetConstructors()[0]; and then .SetResultTransformer(Transformers.AliasToBeanConstructor(constructor)); before the .List() addendum I've looked at my code (because I've already done this one or two years ago :) ), and I noticed that I preferred Type constructor =...
c#,linq,nhibernate,linq-query-syntax
Generic parameters are compile type construct. In your case you specify a string (runtine entity) as a type name, so you need to create a closed generic method instance at runtime via reflection. Next code demonstrates this: Suppose I have: public void Query<T>() { Console.WriteLine("Called Query with type: {0}", typeof(T).Name);...
nhibernate,nhibernate-queryover
The alias used is the name of the variable. So Projections.Property("custAlias.DOB") (can't test now, but if I remember corretly it works) Interestingly, it isn't the variable, in itself, that is used as the alias, but its name. What does it means? QueryOver<Campaign> query; { Customer custAlias = null; query =...
c#,nhibernate,many-to-many,nhibernate-mapping
Your mapping seems to be correct. Just not sure what is the session default FlushMode. To be sure, that it is not None, try to append into first using the session.Flush();. using (ISession session = NHibernateHelper.OpenSession()) { ... session.Flush(); } Reason why simple insert into User and Role is happening...
c#,nhibernate,concurrency,castle-windsor
So i researched and it seems that NHibernateIntengrationFacility doesnt support this transaction management out of the box. I solved it when i changed to new Castle.NHibernate.Facility which supersede Castle.NHibernateIntegration - please note that this is only beta version currently. Castle.Nhibernate.Facility supports session-per-transaction management, so it solved my problem completely....
c#,asp.net,asp.net-mvc,nhibernate,nhibernate-mapping
The issue caused by:"a boolean field in your Project class may be marked as a varchar field in the database". I have a database column "ON_DIALYSIS" "VARCHAR2(1)", it was mapping as a bool in mapping class PatCon public virtual bool OnDialysis { get { return _onDialysis; } set { _onDialysis...
c#,linq,nhibernate,fluent-nhibernate
In both examples from Brenda are missing the transformation. Disclaimer: Check first if the types are correct in the DTO or in the Linq projection. public class MyDto { public string Corporation { get; set; } public DateTime? CalculationDate { get; set; } public string ValuationRule { get; set; }...
c#,nhibernate,fluent-nhibernate
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...
c#,nhibernate,fluent-nhibernate
I. PERSISTING, executing sql write command as discussed in the comments, the first thing we need to make that all happened is to extend the our code with a ISession.Flush() 9.6. Flush (some cite) ... Except when you explicity Flush(), there are absolutely no guarantees about when the Session executes...
c#,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I found the fix for the problem: The fix for the problem is to add Inverse to the mapping of the parent file. So, the mapping for Department will be: DepartmentMap : ClassMap<Department> { Table("...."); HasMany(x => x.Employees).KeyColumn("DeptId").Inverse().Not.KeyNullable(); } ...
c#,.net,nhibernate,fluent-nhibernate,nhibernate-configuration
I wish to have the answer, but mine is: no. We have to pass this values as a setting. The reason is the way how is the table hi-lo generator implemented. Check the TableHiLoGenerator code .Configure() /// <summary> /// Configures the TableHiLoGenerator by reading the value of <c>table</c>, /// <c>column</c>,...
c#,nhibernate,fluent-nhibernate
This turned out to be as I expected a mapping issue but it was really hard to find. The issue was with the related properties: public virtual CnSubGroup CnSubGroupOut { get; set; } public virtual CnSubGroup CnSubGroupIn { get; set; } The CnSubGroup entity also has a version mapping and...
c#,nhibernate,db2,nhibernate-mapping,nhibernate-4
That error doesn't seems to be connected to problems with the foreign keys. It seems to be that the NHibernate can't find the XML files. The "common" problems are normally three: The XML files must be set (in their Properties) with the Build Action = Embedded Resource In the configuration...
I have never used mapping by code, but i assume this is the solution: List(x => x.Students, l => { l.Where("deleted = 0"); l.Key(k => { k.Column("post_id"); k.NotNullable(true); }); l.Schema(Constants.DatabaseSchemaNames.Article); l.Table("tag_post"); }, x => { x.ManyToMany(m => m.Column("tag_id")); }); ...
I don't think you should be using WhereAll in this case. Does this work: query.WithSubquery.WhereProperty(p => p.Id) .In(QueryOver.Of<Product>() .JoinAlias(x => x.Suppliers, () => productSupplierAlias) .Where(() => productSupplierAlias.Product.Id == productAlias.Id) .Where(() => productSupplierAlias.SupplierProductNumber == searchtext) .Select(p => p.Id) ); ...
The way I stopped getting the above exception was to uninstall TeamCity and remove my application's website from IIS Manager. To be clear, I don't think the problem was with TeamCity--the problem was that I ran a build to deploy my application, which added the website to IIS and caused...
c#,nhibernate,oracle11g,fluent-nhibernate
It turns out that it was the visual studio 2015 preview that was somehow messing up something related to oracle libraries which led to this error. I had to reformat my pc couple of times until I understood whats going on.
hibernate,nhibernate,fluent-nhibernate,informix,informixdb
After studies in the customer environment and logs it was found that the error occurred due to completion of a backup in a certain schedule that caused instability in the bank resulting in connection error and after that the the application did not work properly need to be restarted (the...
In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion: // the projection of the column with xml // casted to nvarchar var projection = Projections .Cast(NHibernateUtil.StringClob , Projections.Property("thatXmlFieldWhichIsMappedAsString")); // criteria filtering with LIKE var criteria = Restrictions.Like(projection, "searched...
I removed this from AssemblyInfo.cs: [assembly: log4net.Config.XmlConfigurator(Watch = true)] And added the following just before creating Configuration instance: log4net.Config.XmlConfigurator.Configure(); var cfg = new Configuration(); // creating Configuration instance And it created the folder containing log file. I even changed attribute: <appendToFile value="false" to <appendToFile value="true" so that file will not...
From what I understand, the OnDelete, OnUpdate, ... are used to do things like validation, or modify the actual entity being deleted, updated, inserted. This occurs pretty much at the start of the pipeline, see e.g. "NHibernate interceptor magic tricks, pt. 4" When a delete occurres, the very first thing...
c#,nhibernate,fluent-nhibernate
Based on the Exception I would say, that we can face this issue in case - that the calling side looks like this: var list = ByParameter<MenuItem>("ParentId", 123); And because the snippet above does not show that class MenuItem contains ValueType (non-reference) property ParentId: public class MenuItem { // the...
nhibernate,asp.net-web-api,dependency-injection,automapper,structuremap
I believe @RadimKöhler is right. Your parent container (where the AutoMapper types are configured) doesn't have access to the plugin types defined in the nested container. It just doesn't know about the ISession plugin type hence the exception you get. I can think of a couple solutions here. DISCLAIMER I...
c#,nhibernate,fluent-nhibernate
Manual deletion of the collection items is not a solution. It in facts breaks the cascading feature. In case we do have mapping Cascade.AllDeleteOrphan(), we should expect that deletion of Parent will deleted Children as well - no need to do more then delete Parent. Just ... NHibernate does not...
asp.net,asp.net-mvc,nhibernate,asp.net-mvc-5,nhibernate-mapping
found the answer. it seems scheme key is changed in new nhibernate version changed <hibernate-configuration xmlns="urn:nhibernate-configuration-version-2.2"> to <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> fixes the problem. Im sure because I retested back the first scheme. and boM! same error throw. so xmlns string is updated. how I found it. opened web.config>xml in menu>Schemes [added...
As pointed out in the comments, this is more of a SQL query issue than an NHibernate one. I resolved it by improving the logic of the full query to minimise the number of disjunctions and conjunctions produced.
c#,nhibernate,nunit,nhibernate-configuration
I would suggest to use full path in the connection string: // instead of this <property name="connection.connection_string" >Data Source=MyFirstNHibernateProject.sdf</property> // we should use <property name="connection.connection_string" >Data Source=C:\MyFirstNHibernateProject\MyFirstNHibernateProject.sdf</property> Where the "C:\MyFirstNHibernateProject\" should be the full path to the "MyFirstNHibernateProject.sdf" Also, in case you are suing CE 4.0 I would suggest to...
Future allows to execute two or more sql in a single roundtrip, as long as the database supports it. It's also almost transparent, so you'll want to use Futures whenever possible. If NHibernate can't execute the queries in a single roundtrip, it will execute the queries in two or more,...
c#,nhibernate,nhibernate-queryover
I would say, that solution here should be surprisingly simple and elegant (but only if I do read your issue correctly). The point is - check your params in C#, do not send that into DB side: Exam examAlias = null; var query = session.QueryOver(() => examAlias); //here we will...
c#,postgresql,nhibernate,fluent-nhibernate,domain-driven-design
You can use a json (or jsonb if your postgres version supports it). I wouldn't do that in this case. In order to get the best use out of indexes and data searching, it'd be best to come up with a structure that kept the different data types in different...
nhibernate,queryover,nhibernate-queryover,nhibernate-projections
I expect, that you experience an issue with generated keyword "AS" inside of the ORDER BY in case, that you pass projections like this: // NHibernate will leave few AS, except the last query.OrderBy(sortProjectionList).Asc(); To avoid that, we can do it like this: // NHibernate will solve each projection separately...
nhibernate,oracle11g,fluent-nhibernate,decimal,buffer-overflow
So, what I have figured out is as follows:- Database column is float(126) which has more precision than supported by .NET hence, in some cases exception is thrown when .NET cannot handle the data (overflow). (Oracle number to C# decimal) When a formula is specified in fluent mapping, a column...
c#,nhibernate,fluent-nhibernate,lazy-loading
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...
c#,nhibernate,fluent-nhibernate,fluent-nhibernate-mapping,automapping
I've found the solution: Conventions.Find allows to find convention instances. var map = AutoMap.AssemblyOf<AutomappingConfiguration>(new AutomappingConfiguration()) .Conventions.AddFromAssemblyOf<AutomappingConfiguration>() .UseOverridesFromAssemblyOf<AutomappingConfiguration>(); foreach (var c in map.Conventions.Find<TableConvention>()) { c.AllWritable = allWritable; } ...
.net,nhibernate,fluent-nhibernate
Option 1 session.Clear(); // to get rid associations of the objects in memory session.CreateQuery("delete from MyClass").ExecuteUpdate(); foreach(var entity in CreateNew()) session.Save(entity); Option 2 session.CreateQuery("delete from MyClass where Id not in (:ids)") .SetParameterList("ids", newIds) .ExecuteUpdate(); foreach (var id in newIds) { var entity = session.Get<MyClass>(id); // returns the cached instance if...
This aproach, would be working only if the root entity (Article) would have composite key: <class name="Article" table="article"> // not and <id> mapping <!--<id name="Id" column="articleID" unsaved-value="-1" type="Int32"> <generator class="identity" /> </id>--> // but <composite-id> <composite-id> <key-property name="Id" column="articleID" ></key-property> <key-property name="PublicNumber" column="articleNum"></key-property> </composite-id> <property...
Something like this should fetch all your data in one go: AuthorBook authorBooks = null; Book book = null; session.QueryOver<Author>() .Where(x => x.Id = AuthorId) .JoinAlias(a => a.AuthorBooks, () => authorBooks,JoinType.LeftOuterJoin) .JoinAlias(() => authorBooks.Book, () => book) .SingleOrDefault(); ...
sql-server,nhibernate,sql-server-performance
The simple answer is: No. NH cannot generate "optimal queries" the way you do with hand written queries. It usually gets data from the database to create objects in memory. So for instance, by default it always selects all columns in a table. It tries to optimize SQL compilation time...
c#,.net,generics,nhibernate,queryover
We need to add 1) aliases to each column and use 2) transformer: // Users u - will serve as an alias source below Users u = null; IList<Users> users = this.Session.QueryOver<Users>() .Where(f => f.role == role) .SelectList(list => list // here we set the alias .Select(p => p.username) .WithAlias(()...
c#,sql-server,nhibernate,fluent-nhibernate,hql
The point here is CROSS JOIN if there are no mapped relations, JOIN on existing (mapped) relations. So, in case, there is no mapped relation Question to Answer - we still can query it like this: // instead of INNER JOIN we use 'comma' to produce CROSS JOIN // instead...
c#,nhibernate,timestamp,fluent
If you mean map a DateTime property as this: <property name="Timestamp" type="Timestamp"/> This is the equivalent in Fluent NHibernate: Map(x => x.Timestamp).CustomType<TimestampType>(); ...
c#,mysql,nhibernate,nhibernate-mapping
The point here is that for both many-to-one and one-to-many we have to use the same column "CompanyId" The Company.hbm.xml <bag name="Clients" table="Client" lazy="false" cascade="all" inverse="true" > <!-- wrong column name, it must be parent reference in a child table --> <!-- <key column="ClientId"></key> --> <key column="CompanyId" /> <one-to-many class="ConsoleApplication1.Client,...
c#,nhibernate,orm,nhibernate-mapping
Just few hints, summarizing the most suitable standards I found out when working with NHibernate. 1) If there is a bi-directional reference in persitence (DB column), express it in C# code bi-directional as well. Other words, if a child has reference to parent, parent should have reference to child. public...
c#,nhibernate,nhibernate-criteria
I would like to share my approach, maybe not the answer... I. avoid fetching one-to-many (collections) When creating any kind of complex queries (ICriteria, QueryOver) we should use (LEFT) JOIN only on a start schema. I.e. on many-to-one (References() in fluent). That leads to expected row count from the perspective...
c#,nhibernate,orm,nhibernate-mapping
Found the correct way to do this: use a <many-to-one> mapping with an added unique constraint: <many-to-one name="Registration" class="UploadedDocument" column="RegistrationID" unique="true" /> For further reference: 5.1.12. one-to-one...
nhibernate,nhibernate-mapping,hibernate-mapping,mapping-by-code
The where should belong to many-to-many as in the xml mapping Set(x => x.SystemRoles, m => { // set mapping }, col => col.ManyToMany(p => { // mapping of the many-to-many p.Column(x => x.Name("PrivilegeId")); p.Where("PrivilegeType = 'SystemRole'"); }) ); But not fully sure, if all features are already supported in...
nhibernate,fluent-nhibernate,queryover,nhibernate-queryover
The point here is a difference in our need of paging and its implementation. while we would expect 5 root elements to be returned, the result is converted into 5 rows, 5 selected rows : Some clue could be found in this Q & A: NHibernate QueryOver with Fetch resulting...
c#,sql-server,nhibernate,fluent-nhibernate,nhibernate-mapping
The way to go in case we need the skip the mapped relationship mapping (when CROSS JOIN with WHERE clause is needed) we can use HQL (only way, check e.g. here:) How to join Two tables of two non relashinship defined columns using Nhibernate QueryOver Nhibernate QueryOver JoinAlias UnRelated Entity...
c#,nhibernate,hql,criteria,restrictions
What we would need is Sub-SELECT. This could be achieved with subquery. 15.8. Detached queries and subqueries We can define subquery with DetachedCriteria: var subquery = DetachedCriteria.For<OrderItem>() .Add(Restrictions.Eq("FinalDeliveryIndicator", true)) .SetProjection(Projections.Property("OrderId")); This would later end up as this SQL snippet: (SELECT OrderId FROM OrderItems WHERE FinalDeliveryIndicator = 1 ) And this...
nhibernate,nhibernate-projections
To return constant, we can use Projections.Constant() methods: // Projections.Property("This Year Issue Price").WithAlias(() => sProduct.PriceTitle) Projections.Constant("This Year Issue Price").WithAlias(() => sProduct.PriceTitle) NOTE: But, there really should be some reason, for this, because we send that value to DB, then recieve it as many times as many records we get. Maybe...
There are only two ways how to solve this. 1) do not use inverse="false" <bag name="tableB" lazy="true" inverse="true" // instead of false batch-size="25" cascade="all-delete-orphan"> <key column="tabAId" /> <one-to-many class="tableB" /> </bag> This setting (inverse="true") will instruct NHibernate to directly delete an item from DB. While using inverse="false" will in general...
nhibernate,nhibernate-mapping,mapping-by-code
Replaced the many to many with one to many and introduced an entity that represents the relationship (followed advice from this article). This has the upside of allowing you to map the order-by column as well as other columns, and also solved the issue of restricting the number of items...
You can use Expression trees and build something like: protected T Get<T, TValue>(string propertyName, TValue value) where T : class { var par = System.Linq.Expressions.Expression.Parameter(typeof(T), "x"); var eq = System.Linq.Expressions.Expression.Equal(System.Linq.Expressions.Expression.Property(par, propertyName), System.Linq.Expressions.Expression.Constant(value)); var lambda = System.Linq.Expressions.Expression.Lambda<Func<T, bool>>(eq, par); return...
If you are wanting to read updates you have made within a transaction these should already be available to you in memory if you are using the same session that is doing the updates. If you however want to read uncommitted rows via another session you will probably have to...
c#,xml,visual-studio-2010,nhibernate
Add not-null="true" and update="false" to Paciente collection mapping: <bag name="Paciente" cascade="all-delete-orphan"> <key column="ciPaciente" not-null="true" update="false"/> <one-to-many class="Paciente" /> </bag> Also, probably you want to map the collection as inverse....
Judging by that error, your repository is trying to delete the a user from its table but that user is referenced in another table (dbo.Invoices). So you are seeing a foreign key constraint error where you are trying to delete a record who's primary key is referenced in another table...
nhibernate,fluent-nhibernate,sessionfactory,uptime
Couple of comments that might help you. You can serialise your sessionfactory after its been built. See this blog post for more info. Or Google serialise sessionfactory nhibernate as there are alot of articles If this is a web site then I would always make sure it is spun up...
c#,nhibernate,queryover,nhibernate-queryover
Solution here would be to use a bit different interface IQueryOver<Product, Product> For example, we can see how it works in the doc of the 16.5. Aliases: Cat catAlias = null; IQueryOver<Cat,Cat> catQuery = session.QueryOver<Cat>(() => catAlias) .... Check the source code here /// <summary> /// QueryOver<TRoot,TSubType> is an API...
sql,nhibernate,nhibernate-queryover,nhibernate-projections
You need a subquery... Children childrenAlias = null; var subquery = QueryOver.Of<Children>(() => childrenAlias) .Where(() => childrenAlias.Parent.ID == parentAlias.ID) .ToRowCountQuery(); query.WithSubquery.WhereValue(2).Le(subquery); Note that I don't know how to do Count > 2, so I'm doing 2 <= Count, and there is the possibility that instead of .Where(() => childrenAlias.Parent.ID ==...
c#,sql-server,nhibernate,hql,user-defined-functions
You won't be able to use RegisterFunction for this. That's for registering scalar functions. However, you can create a named query and execute that instead. That involves a few steps though: Create the named query XML file. This must end in *.hbm.xml. I find it useful to keep the name...
Well, firstly NHibernate is ORM. ... In object-oriented programming, data management tasks act on object-oriented (OO) objects that are almost always non-scalar values. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be...
Detached objects (loaded in one session, and kept as reference) could be re-attached. We can use session.Merge() or session.Lock() 9.4.2. Updating detached objects Many applications need to retrieve an object in one transaction, send it to the UI layer for manipulation, then save the changes in a new transaction.... ......
select,nhibernate,case,queryover
I think this should do the trick: session.QueryOver<MyTable>() .Select( Projections.Group<MyTable>(x => x.Id), Projections.Sum( Projections.Conditional( Restrictions.Eq( Projections.Property<MyTable>(x => x.MyValue), 1), Projections.Property<MyTable>(x => x.Volume), Projections.SqlFunction( new VarArgsSQLFunction("(", "*", ")"), NHibernateUtil.Int32, Projections.Property<MyTable>(x => x.Volume), Projections.Constant(-1))))) .List<object[]>(); As a rule, QueryOver is pretty terrible at...
c#,nhibernate,fluent-nhibernate,postgis
I was finally able to resolve this by defining a custom UserTypeConvention, i.e.: using NetTopologySuite.Geometries; using NHibernate.Spatial.Type; public class PostGisPolygonUserTypeConvention : UserTypeConvention<PostGisGeometryType> { public override void Accept(IAcceptanceCriteria<IPropertyInspector> criteria) { criteria.Expect(c => c.Type == typeof(Polygon)); } public override void Apply(IPropertyInstance instance) { // Have to set CustomType to be able to...
So I got this working - using Criteria rather than HQL. The solution was the following. var criteria1 = DetachedCriteria.For<Server>() .Add(Restrictions.Eq("ServerID", s.ServerID)) .SetFetchMode("Adapters", FetchMode.Eager) .CreateCriteria("Adapters", JoinType.LeftOuterJoin); var criteria2 = DetachedCriteria.For<Server>() .Add(Restrictions.Eq("ServerID", s.ServerID)) .SetFetchMode("Configurations", FetchMode.Eager) .CreateCriteria("Configurations", JoinType.LeftOuterJoin); var result = Session.CreateMultiCriteria()...
c#,linq,nhibernate,fluent-nhibernate
To solve issue with mixed upper/lower, we can just convert both sides into .ToLower() return Session.Query<Person>() .Where(r => (r.LastName.ToLower().Contains(s.ToLower()) || r.FirstName.ToLower().Contains(s.ToLower()))); Check this link for more details how the NHibernate native InsensitiveLikeExpression.cs is working (for almost every dialect it is doing the same) : NHibernate IsInsensitiveLike treats strings as case...
c#,nhibernate,connection-string,castle-windsor,castle-activerecord
I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.) Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here....
asp.net-mvc-4,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
You can use component mapping: Component(x => StoreAddress).ColumnPrefix("StoreAddress"); Component(x => OfficeAddress).ColumnPrefix("OfficeAddress"); Then create a component map for Address type: public class AddressMap : ComponentMap<Address> { public AddressMap() { //map properterties } } ...
c#,nhibernate,fluent-nhibernate
use a subquery to filter out TableA elements having null values in tabB-Items var subquery = QueryOver.Of<TableA>() .JoinQueryOver(tabA => tabA.TableBItems) .Where(tabB => tabB.X == null || tabB.Y == null) .Select(Projections.Id()); var s = Session.QueryOver<TableA>() .Where(tabA => tabA.SomeID == 123 && tabA.SomeNullableDate != null) .WhereRestrictionOn(Projections.Id()).NotIn(subquery) .JoinQueryOver(tabA => tabA.TableBItems) .Where(tabB => tabB.X...
nhibernate,fluent-nhibernate,domain-driven-design
The only way I managed to move forward (using the private field) was to set a global Access.Field convention. .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Customer>() .Conventions.Add(DefaultAccess.Field()))...
entity-framework,nhibernate,orm,repository-pattern,unit-of-work
Personally i think your approach is solid. But equally Im surprised you see this approach as very different to the repository / Unit of Work Pattern. Your IService layer is directly comparable to a basic Unit of Work layer combined with a repository layer implemented via an interface. The repository...
c#,nhibernate,nhibernate-mapping
You, and Ayende in the link you gave, are creating queries in HQL using the CreateQuery method. This type of NH query must be written against NH entities, which means you must have a proper mapping, i.e. a Sales entity, and then write select count(*) from Sale as Ayende selects...
public class User : Auditable { int Id; string Username; } public class Auditable : IAuditable { public virtual int CreatedBy { get; set; } } public class AuditEventListener : IPreInsertEventListener { public bool OnPreInsert(PreInsertEvent @event) { var audit = @event.Entity as IAuditable; if (audit == null) return false; var...
For the same reasons. If your methods are not virtual, then NHibernate would not be able to initialize proxy. Just consider following code: public class A { private int _a; public virtual int A { get { return _a; } set { _a = value; } } public void DoSomethingWithA()...
nhibernate,nunit,nhibernate-mapping,spring.net
To resolve the above issue, performed several steps, though I'm not sure specifically which one fixed it: Added reference to NHibernate.Validator, Version=1.3.1.4000 in my test project and NHibernate.Caches.SysCache, Version 3.1.0.4000 Added reference log4net, Version=1.2.10.0 to my test project to print out more diagnostic info Added references to System.Configuration, System.Web.ApplicationServices, and...
c#,entity-framework,nhibernate,multi-database
using NHibernate (with FluentNHibernate) and code it would be like using NHCfg = NHibernate.Cfg; var config = new Configuration().AddMappingsFromAssembly<Entity>(); if (UseSqlCe) { config.SetProperty(NHCfg.Environment.Driver, typeof(SqlCeDriver).AssemblyQualifiedName); config.SetProperty(NHCfg.Environment.Dialect, typeof(SqlCeDialect).AssemblyQualifiedName); } else if (UseSqlite) { config.SetProperty(NHCfg.Environment.Driver, typeof(Sqlite20Driver).AssemblyQualifiedName); config.SetProperty(NHCfg.Environment.Dialect,...
c#,sql-server,database,entity-framework,nhibernate
If you are choosing to use int keys because of migrating to EF, you actually don't need to change it, and you can keep the existing data, have a look at this. But if you need to move to int keys for some other reason, it's going to be hard...
c#,nhibernate,fluent-nhibernate,automapper
You must add a condition to validate if the collection is initialized to be mapped. You can read here more details: Automapper: Ignore on condition of. AutoMapper.Mapper.CreateMap<DictionaryEntity, DictionaryDto>() .ForMember(dest => dest.DictionaryRecord, opt => opt.Condition(source => NHibernateUtil.IsInitialized(source.DictionaryRecord))); ...
c#,nhibernate,fluent-nhibernate,multi-tenant,fluent-nhibernate-mapping
Not tested, but you can set in the SessionFactory (technically in its configuration) the default schema name. The property is hibernate.default_schema. So you could have multiple SessionFactory, one for each schema. Clearly you mustn't set the scema name at the Entity level. Something like: var config = new Configuration(); ......
It turns out that it was a scoping issue. I had to change the code to the following to the following: Category category = null; using(var lifetime = container.BeginLifetimeScope()) { ICategoryRepository categoryRepository = lifetime.Resolve<ICategoryRepository>(); DefaultCommandBus commandBus = lifetime.Resolve<DefaultCommandBus>(); IMappingEngine mapper = lifetime.Resolve<IMappingEngine>(); category = categoryRepository.Get(x => x.Title == "Updated Category...
datetime,nhibernate,configuration,fluent-nhibernate,utc
The way with fluent NHibernate is Convention Conventions James Gregory edited this page on 3 Apr 2012 · 1 revision ... The conventions are built using a set of interfaces and base classes that each define a single method, Apply, with varying parameters based on the kind of convention you're...
I would say, that this should be up to us (our code) not NHibernate. We can use this: How do I escape a percentage sign in T-SQL? i.e. replace any % in C# with [%] lel[%]lel And this would return what expected .Where(x => x.attr.Contains(query)) // query == "lel[%]lel" ...
c#,oracle,nhibernate,fluent-nhibernate
I guess that we should change the select. It should not be using the current table DOCLIST (which is alreaedy used for mapping the root class Doc .. Table("DOCLIST")) // current select (SELECT Distinct A.CODE FROM DOCLIST D Left Join DOCSLINKS DL On DL.TODOC_ID=D.DOC_ID Left Join ARTICLES A On DL.ART_ID=A.ART_ID...