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...
hibernate,nhibernate,orm,fluent-nhibernate,fluent-nhibernate-mapping
The mapping HasManyToMany would expect to have entity/object not ValueType - on the other side of many-to-many. Also many-to-many reuires the pairing table. The mapping we need here is the HasMany and for ValueType like Decimal we need .Element() mapping: HasMany(x => x.Links) .Table("A_Link_Value_Map") .KeyColumn("A_Id") .Element("Link_Value") // Value Type would...
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...
c#,nhibernate,fluent-nhibernate,usertype
You should try upgrading fluent nhibernate. Please take a look at known issue https://github.com/jagregory/fluent-nhibernate/issues/210
c#,sqlite,nhibernate,fluent-nhibernate
I noticed that you are naming your columns (ParentKeyColumn and ChildKeyColumn). If you just name you table and call Inverse() or Cascade.All(), it will work as you want, due to the fact that fluent nhibernate will create both columns and manage by itself. On your ProjectMap, you can do this:...
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))); ...
nhibernate,fluent-nhibernate,lazy-loading,nhibernate-mapping,fluent-nhibernate-mapping
Just call: session.GetSessionImplementation().PersistenceContext.Unproxy(entity)...
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...
c#,fluent-nhibernate,fluent-nhibernate-mapping
On first sight, I actually noticed two possible problems with your code. First: Have you tried to profile your generated SQL? With a profler tool like NHProf. Edit: Another option for logging could be, if you extend the FluentConfiguration setup by adding: .Diagnostics(d => d.Enable(true)) .Diagnostics(d => d.OutputToConsole()) Where as...
c#,asp.net,sql-server-2008,fluent-nhibernate
I use the following syntax to define an NVARCHAR(MAX) column when mapping with Fluent NHibernate: const int NVarCharMax = 4001; // force NHibernate to allocate max length for nvarchar data Map(x => x.ColumnName).Length(NVarCharMax); This article describes the solution in more detail....
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; }...
nhibernate,fluent-nhibernate,ninject
Since you're using Ninject, my recommendation is to use it to inject the session factory rather than an IHttpModule. To do so, create Ninject Provider classes as shown below. Note that this requires transaction management in code, I dislike the idea of blindly holding a transaction open during a request....
.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...
c#,nhibernate,fluent-nhibernate
I'm not sure what exactly you are asking here, but I'll try to answer what I think you are asking. In order to map a many-to-many relationship to the database with Fluent NHibernate for the classes in your question would be as simple as public class ActorMap : ClassMap<Actor> {...
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...
c#,nhibernate,fluent-nhibernate,nhibernate-mapping
I tried explain what is happening in detail here NHibernate Deleted object would be re-saved by cascade Delete an item from many-to-many relationship I would say, that the point is here: the ProgramItem is referenced by some other collection. And that collection was also loaded into the session. The best...
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>,...
Make sure that your entity and mapping classes are public. Properties for your entities i.e. database fields should be public virtual. Also try specifying the assembly of a mapping class instead of using GetExecutingAssembly(), I do vaguely recall experiencing trouble with it when I tried setting up FNH for the...
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...
nhibernate,fluent-nhibernate,many-to-many,nhibernate-mapping,cascading-deletes
The answer is (I am really sure) here: NHibernate Deleted object would be re-saved by cascade Let me re-phrase that for your case, what could happen: we remove an GrupoArquivo from ArquivoRetorno.GrupoModulos collection. During that transaction, unit of work, we also tuch and therefore load the GrupoModulo GrupoModulo gets initiated...
c#,nhibernate,fluent-nhibernate,firebird
NHibernate could help us to map Tables into C# objects / entities (ORM). That means: we should properly map ALL table's columns into ALL C# entity properties. Later (e.g. business layer or inside of the get and set) we should apply some validation rules to achieve required behaviour. Also we...
c#,nhibernate,fluent-nhibernate
The solution to 1 + N would've been built on top of a special NHibernate optimization feature (let me cite a bit) 19.1.5. Using batch fetching NHibernate can make efficient use of batch fetching, that is, NHibernate can load several uninitialized proxies if one proxy is accessed (or collections. Batch...
.net,vb.net,nhibernate,fluent-nhibernate
In the end it was unnecessary to use the access modifiers, or go through a field. I just had to map it as ReadOnly and it was able to automatically pick up the correct field to use when storing the data. For some reason I was under the impression that...
fluent-nhibernate,save,duplicates
Okay, so I did basically what I said I thought would work (and it did): using (ITransaction transaction = session.BeginTransaction()) { foreach (WorkOrderTask t in WorkOrder.Tasks) { if (t.EquipmentComponent != null) { session.SaveOrUpdate(t.EquipmentComponent); session.Flush(); session.Clear(); } } session.SaveOrUpdate(WorkOrder); transaction.Commit(); } saving each component first, flushing and clearing the session between...
fluent-nhibernate,fluent-nhibernate-mapping
To use NHibernate's mapping support for CultureInfo (which is there, see https://github.com/nhibernate/nhibernate-core/blob/c85d038dce8ba87bd3f4de2458b4ef6e2497f7f8/src/NHibernate/Type/CultureInfoType.cs), you'll need to tell Fluent NHibernate you want to use it by means of the following convention: using System.Globalization; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.AcceptanceCriteria; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.Conventions.Instances; public class...
c#,nhibernate,fluent-nhibernate,db2400
As of December 2014, you still cannot fix this issue: https://github.com/jagregory/fluent-nhibernate/issues/272 It makes sense because it's an ORM and we were trying to use it on a database without properly enforced relationships (the keys are missing but the data behaves this way). This issue has forced my company to drop...
c#,nhibernate,fluent-nhibernate
Try to use joined table. public class SomeClassMap : ClassMapping<SomeClass> { public SomeClassMap() { Table("SomeClassTable"); Property(p => p.SomeClassID, map => { map.Column("SomeClassID"); map.Generator(Generators.Identity); }); Property(p => p.ClassTypeID, map => map.Column("ClassTypeID")); //Other properties here Join("SomeClassTypes", m => { m.KeyColumn("ClassTypeId"); m.Fetch.Join(); m.Map(x => x.DescriptionType).Column("Description"); }) } } EDITED If you use fluent...
This happens when there is a problem with your mapping. The main exception doesn't tell you much more than that. You need to dig down to look at the text of the inner exceptions, then it is should typically become very clear what the problem is. Edit: Just to add,...
c#,nhibernate,fluent-nhibernate
Solution you've used could be convertied into standard ORM use case. The native or object/entity oriented solution here would be to introduce many-to-one and one-to-many mappings. That would bring lot of benefits (lazy loading == only if needed, querying...) Small note, I am expecting that the FORMULA snippet in the...
mysql,vb.net,nhibernate,fluent-nhibernate,fluent-nhibernate-mapping
I would suspect that Index could be a keyword for MySQL. To avoid such conflict, we can define different Index column name (sorry for C# notation) HasMany(x => x.PolygonData) .AsList(idx => idx.Column("indexColumnName").Type<int>()) ...
c#,nhibernate,fluent-nhibernate
The good is, that all is working properly. And your mapping is correct. Because if this snippet is working... // This works existingChild.CreateParent(parameters); session.Save(existingChild); transaction.Commit(); ... the concept is working as well. Why? What is all about? Why Commit() helped to solve that? Well, because ISession is an abstraction, it...
c#,nhibernate,fluent-nhibernate,nhibernate-mapping,one-to-one
OK, with assignable ID we can do it like this. Firstly we should be sure, that the ID is assigned, so we can adjust the getter of the <id> ItemSaleCode like this: public class ItemSaleDetail { string _itemSaleCode; public virtual string ItemSaleCode { get { return _itemSaleCode ?? SaleParent.SaleCode ;...
c#,nhibernate,fluent-nhibernate,lazy-loading
I would put it this way: Lazy loading is the essence of ORM. It is the principle of ORM. (unless we want to load complete DB in one shot) Check this article by Ayende: NHibernate is lazy, just live with it small cite from that source: ...There is a good...
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...
Properties need to be virtual for nhibernate so that they can be substituted with proxies (required for lazy-loading) You don't have to do that.However, it is a good practice to initialize collections in the constructor so that you don't get null suddenly in the code. For example , consider...
c#,join,nhibernate,fluent-nhibernate,nhibernate-queryover
In your case, the only problem is, that you do not provide Expression inside of the .Where(), so this should do the job: // instead of this // .Where(clientTechnology.Client == client) //this doesn't compile // use this .Where(() => clientTechnology.Client == client) But I would go even farther. We should...
c#,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I would say, exactly as you pointed out in your comment: I actually do have the RelationTable mapped with 2 many-to-one references to Person (as PersonA and PersonB). Using one-to-many (HasMany), how then do you suggest I map Sons and Daughters (both List<Person>) in the Person class taking into account...
mysql,nhibernate,orm,fluent-nhibernate,hql
I made a stored procedure in de MySQL database DELIMITER // create procedure getTrending (IN $getClimbers bool, IN $fromDate DateTime, IN $nrOfTrending int) Begin if ($getClimbers) then select p.id, p.active, p.title, p.comments, sum(case when r.isUpvote = b'1' and r.date > $fromDate then 1 else 0 END) - sum(case when r.isUpvote=b'0'...
nhibernate,fluent-nhibernate,expression-trees,nhibernate-queryover
I have a doubt the error is there: Expression<Func<MyClass, bool>> mc1 = x => (x.ID > 20); Expression<Func<MyClass, bool>> mc2 = x => x.ID > 20; var body1 = mc1.Body.NodeType; // GreatThan var body2 = mc2.Body.NodeType; // GreatThan The brackets are removed by the compiler. There is nothing in the...
c#,nhibernate,fluent-nhibernate,nancy
You are right, conversion from ID into Entity (Applicaton) will require call to data layer and its operation GetById(). session.Load<Application>(id) In cases, that we can be sure, that the passed Application ID exists, NHibernate has a dedicated way how to convert ID into its ENTITY. It is a Load() method,...
Assuming your domain class is TR_DISTAKENEVTVIEW int wocount = session.Query<TR_DISTAKENEVTVIEW>().Select(x => x.wo).Distinct().Count(); To use .Query() method you will have to use using NHibernate.Linq; namespace on the top...
c#,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
After all, with these SQL scripts (adjust for SQL Server in my case) CREATE TABLE CLIENTE ( CORE_ID int NOT NULL, CORE_NUMERO_MEDIDOR VARCHAR(50) ) CREATE TABLE MEDIDOR ( NUMERO_MEDIDOR VARCHAR(50), MARCA_MEDIDOR VARCHAR(50) ) With these entities (all properties are virtual) public class Cliente { public virtual int ClienteId { get;...
c#,fluent-nhibernate,linq-expressions
You probably want something like: public static Expression<Func<TSource, bool>> GetEquality<TSource>(object value, params string[] properties) { ParameterExpression pe = Expression.Parameter(typeof(TSource), "source"); Expression lastMember = pe; for (int i = 0; i < properties.Length; i++) { MemberExpression member = Expression.Property(lastMember, properties[i]); lastMember = member; } Expression valueExpression = Expression.Constant(value); Expression equalityExpression =...
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-queryover
You're close: session.QueryOver<PersonEntity>() .Select( Projections.Max( Projections.SqlFunction( new SQLFunctionTemplate( NHibernateUtil.String, "split_part(?1, ?2, ?3)"), NHibernateUtil.String, Projections.Property<PersonEntity>(p => p.Name), Projections.Constant("-"), Projections.Constant(2)))) .SingleOrDefault<int>(); You could also clean this up a bit by registering the function in your own dialect (I'm assuming you're using PostgreSQL: public class CustomPostgresDialect : PostgreSQLDialect { public...
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...
Cfg.Environment.BytecodeProvider.ObjectsFactory is responsible for creating objects used by NHibernate. You can implement IBytecodeProvider to inject your own for example: class MyBytecodeProvider : NHibernate.Bytecode.Lightweight.BytecodeProviderImpl, IObjectsFactory { public override IObjectsFactory ObjectsFactory { get { return this; } } #region IObjectsFactory implementation public object CreateInstance(System.Type type) { // TODO: } public object CreateInstance(System.Type...
vb.net,nhibernate,fluent-nhibernate
An update on this: Having not found a way of updating the composite primary key through NHibernate, I decided to look at adding a new one and deleting the existing one. Although at first I had issues with this, I followed the advice of the answer to this question, specifically...
nhibernate,fluent-nhibernate,left-join,queryover
The way I would go here is: load the list of root entity (Parent) and let NHibernate load their children lazily - in separated SQL query. To avoid 1 + N issue, we can use smart mapping feature: 19.1.5. Using batch fetching NHibernate can make efficient use of batch fetching,...
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,fluent-nhibernate,queryover,iusertype
A quick (possibly not ideal) solution: var specialTypeToCompare = new SpecialType("1", "some_description"); var results = session.QueryOver<Person>() .Where(x => x.SpecialType.Code == specialTypeToCompare).List(); This is probably not ideal though, since you have to fill some fake value in for the description. NHibernate should generate the correct SQL though. Another solution that's a...
c#,visual-studio-2013,fluent-nhibernate,mapping,firebird
I found how do this. In CompositeId have one parameter for add a table reference. public class MapProduction : ClassMap<Production> { public MapProduction() { CompositeId() .KeyProperty(c => c.ProductionCode, "P_PRO") .KeyProperty(c => c.Cycle, "C_CIC") .KeyProperty(c => c.Crop, "C_CUL") .KeyProperty(c => c.TechnologyLevel, "C_NVT"); Map(c => c.Area).Column("A_ARE"); Map(c => c.Productivity).Column("P_ARE"); Map(c => c.syncStatus).ReadOnly();...
c#,fluent-nhibernate,fluent-nhibernate-mapping
in the object model der is no difference between manual mapping and automapping public class Box { public virtual Guid Id { get; set; } public virtual IList<Item> Contents { get; protected set; } public Box() { Contents = new List<Item>(); } public void Add(Item item) { item.Parent = this;...
c#,mysql,asp.net-mvc-4,nhibernate,fluent-nhibernate
I was attempting to join foo and bar on fooid, but bar had its own primary key foobarid. Once I turned on logging for NHibernate, I could see the generated query was incorrect. It was generating: SELECT fb.* FROM foo f INNER JOIN bar b ON f.fooid = b.foobarid INNER...
c#,nhibernate,fluent-nhibernate,fluent-nhibernate-mapping
You should change this: References(x => x.Address).Cascade.All(); References(x => x.CorrespondencyAddress).Cascade.All(); Into this (see .Nullable() setting) References(x => x.Address).Cascade.All(); References(x => x.CorrespondencyAddress).Nullable().Cascade.All(); Check all the available settings here (scroll down to Fluent NHibernate's equivalent) Also check this: public class Patients { ... public virtual int? IndividualId { get; set; } and...
c#,.net,nhibernate,fluent-nhibernate
I am not sure what the real issue is: ...however this will result in all Notes being loaded for every Entity and I only want to load the notes for that particular entity... Is the issue in lazy loading? or in fact that Entity1 and Entity2 can have same ID,...
nhibernate,fluent-nhibernate,nhibernate-mapping
You may not like it, but the table structure described above, is not representing Entity relations you've created (so called one-to-one). In case, that one table contains column referencing the another table (FK), we have scenario: Each Order has exactly one (or null) Invoice. (many-to-one) Invoice can be referenced by...
nhibernate,fluent-nhibernate,fetch,eager,istatelesssession
I would say: Do not use StatelessSession. It does not suite to this use case. 13.2. The StatelessSession interface Alternatively, NHibernate provides a command-oriented API that may be used for streaming data to and from the database in the form of detached objects. A IStatelessSession has no persistence context associated...
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.
The distinct requirement makes this a bit more complicated, but NHibernate already has various date/time methods registered for use in Criteria and QueryOver queries. This is slightly different than the SQL you asked for, but the results should be the same: var distinctDates = session.QueryOver<MyTable>() .Select(Projections.Distinct( Projections.SqlFunction("date", NHibernateUtil.Date, Projections.Property<MyTable>(mt =>...
c#,sql,postgresql,nhibernate,fluent-nhibernate
I would heavily doubt that you'll ever recieve answer for your giant SQL Query - and its conversion. Meanwhile, I would like to point out some differences in approach/thinking when using NHibernate. Use entities first. Define your model, the business domain model with Users, Topics, Boards. Spend some time to...
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()))...
sql,nhibernate,fluent-nhibernate
This is a basic set-within-sets question. I like to solve these using group by and having, because that is the most flexible solution. From what I can see table1 is not actually needed for this: select t2.Table1Id from table2 t2 join table3 t3 on t2.Table3ID = t3.Id group by t2.table1Id...
c#,nhibernate,fluent-nhibernate,nhibernate-queryover
You have to think of your QueryOver query as (nearly) directly translating into SQL. With this in mind, imagine this SQL query: select Album.* from Album where Album.Name = 'SomeAlbumName' and Album.Artist.Name = 'SomeArtistName' This won't work because you can't access a related table's properties like that in a SQL...
c#,fluent-nhibernate,extension-methods
Your extension method is written for IList not IList<T> and because IList<T> does not inherit IList, you need to specify type argument in the extension method: public static class Extensions { public static void Bind<T>(this IList<T> list) { //some stuff } } ...
c#,nhibernate,fluent-nhibernate
This can be achieved with Futures, find the full code below for your example, public class FooBar { public virtual int FooBarId { get; set; } public virtual string FooBarName { get; set; } } public class FooBarMap : ClassMap<FooBar> { public FooBarMap() { Table("foorbar"); LazyLoad(); Id(x => x.FooBarId).GeneratedBy.Identity().Column("foobar_id"); Map(x...
c#,nhibernate,fluent-nhibernate,fluent,fluent-nhibernate-mapping
Your built an entity for the retail price with a complete mapping. AliasToBean transformer does not use mappings but instead mapps columns to properties by convention. Change Transformer to AddEntity: public IEnumerable<TEntity> Fetch(String sql,IEnumerable<Parameter> parameters) { return this.BuildQuery(sql, parameters).AddEntity(typeof(TEntity)).List<TEntity>(); } ...
c#,nhibernate,fluent-nhibernate,quartz.net
This issue was with my Connection String in the Quartz.server.exe, the name was different with the name used in fluent DbConfig method. Updating the name of connection string fixed the issue.
.net,nhibernate,fluent-nhibernate,many-to-many,hql
You can not do this with HQL or Criteria, but you should be able to do this with native sql. session.CreateSQLQuery(@"INSERT INTO UsersToVehicles (VehicleId, UserId) SELECT VehicleId, :userId FROM Vehicles WHERE CategoryId = :categoryId") .SetInt32("userId", userId) .SetInt32("categoryId", categoryId) .ExecuteUpdate(); But instead of doing this consider adding TrackingUsers relation between user...
c#,nhibernate,fluent-nhibernate,queryover,nhibernate-queryover
I think all you need to do is assign the coffee alias in the session.QueryOver<Coffee> call: Coffee coffee = null; session.QueryOver<Coffee>(() => coffee) /* etc */ The below might be completely unrelated to what you're doing, but I figured I'd include it in case anyone else is writing code that...
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...
fluent-nhibernate,lazy-loading,fluent-nhibernate-mapping
the lazy load convention works mostly on list's only, I have tried my fair share of troubles when I tried to use it on non-collection child elements. So yes, you can use .Conventions.Add(DefaultLazy.Always()) but that should be preferred for collections only...
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#,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...
c#,nhibernate,fluent-nhibernate
Formulas are basically raw SQL statements (which will be processed to add aliases), so you can't access inherited properties etc. But you can write a SQL subselect that gives you what you need. (SELECT TOP 1 pt.Delivery + t.Tax + t.Amount FROM ProductTransaction pt INNER JOIN Transaction t ON pt.Id=t.Id...
c#,fluent-nhibernate,fluent-nhibernate-mapping
I solved this by extending the Mappings-call a bit: .Mappings(arg => { var autoPersistenceModel = AutoMap.Source(typeSource); foreach (var overrideType in typeSource.GetOverrideTypes()) { autoPersistenceModel.Override(overrideType); } foreach (var conventionType in typeSource.GetConventionTypes()) { autoPersistenceModel.Conventions.Add(conventionType); } arg.AutoMappings.Add(autoPersistenceModel); }) Unfortunately this is far from elegant or complete - it would be way more decent if...
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,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...
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 } } ...
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...
nhibernate,fluent-nhibernate,fluent-nhibernate-mapping
There's no way to do that. NHIbernate is mimicking what you can do in Sql Server config with cascade-deletes. There's no way to go up to a parent and delete "orphans" without using triggers in Sql Server. There's a way to mimic triggers in NHibernate using "Interceptors" - a way...
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...
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#,asp.net-mvc,fluent-nhibernate
It is being a little difficult to realize what is the source of your problem without the classes, although, a guess would be at the Consumptions property. If it is a list (as it seems by its name) it should be mapped with HasMany instead of References. Besides, maybe you...
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...
fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I think you might need to specify the KeyColumn. I do something similar in one of my solutions and I would map the entities above as follows... mapping.HasMany(x => x.Bars) .Schema("Schema") .Table("FooBars") .Element("Bar") .KeyColumn("FooID") .ForeignKeyConstraintName("FK_FooBar_Foo") .Not.Inverse() .Cascade.All() .Fetch.Select(); This will give a table called Schema.FooBars. It will have a FooID...
c#,sql-server,nhibernate,fluent-nhibernate
Well, after having a look at NHibernate source code I was able to find a solution that works and is not particularly ugly. The key thought is to generate SQL 'IN' expression without using parameters. The first thing to do is make an ICriterion class for this expression. This should...
c#,design-patterns,nhibernate,fluent-nhibernate
I agree with you that an enum would be the better choice. Here is an example of how you could implement this: 1.Create the enum: public enum CardClassId { ClassA = 1, ClassB = 2, ClassC = 3, ... } 2.Change the type of the ClassId property from int to...
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; } ...
c#,sql-server,stored-procedures,nhibernate,fluent-nhibernate
instead of have a dynamic mapping you could issue the query using SQLQuery and transform the results manually using a result transformer public List<Model> CallFoo(ISession session, DateRange range) { return session.CreateSqlQuery("call sproc") .SetParameter(...) .SetResultTransformer(new ModelResultTransformer()) .List<Model>(); } class ModelResultTransformer : NHibernate.Transform.IResultTransformer { public IList TransformList(IList collection) { return collection; }...
mysql,nhibernate,visual-studio-2013,fluent-nhibernate
The point here is the upper/lower case (SQL vs Sql): // wrong MySqlConfiguration // Sql // MUST Be MySQLConfiguration // SQL Check the similar Q & A: MySql.Data.MySqlClient.MySqlConfiguration' does not contain a definition for 'Standard' Fluent NHibernate Here is Question with some snippet showing the right upper/lower case: MySQL Configuration...
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...
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(); ......
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...
c#,nhibernate,fluent-nhibernate
I suggest decoupling components that open session perform db operations with this approach you can keep logic for handling OpenSession() exceptions inside your 1st line and don't worry later. Reason is that if (as in your case) databaseFacade.OpenSession() throws exception you don't have to catch it and check for transaction...
c#,nhibernate,fluent-nhibernate
There is a workaround. But only becuase your many-to-one is readonly (and we do not have to care about insert/udpate issues later). How? By introducing a virtual entity e.g. PanelView // Readonly mapping, virtual class // which ID role is playing column panel_CODE public PanelViewMapping() { Table("panel-table"); Id(x => x.Code)...
asp.net-mvc-5,fluent-nhibernate,fluent-nhibernate-mapping,fluent-migrator
In C#, you must use an equals sign ("=") in the object initializer instead of a colon (":"). Insert.IntoTable("users").Row(new { USERNAME = "superadmin",EMAIL = "[email protected]",PASSWORD_HASH = "dfgkmdglkdmfg34532+"}); Insert.IntoTable("users").Row(new { USERNAME = "admin",EMAIL = "[email protected]",PASSWORD_HASH = "dfgkmdglkdmfg34532+"}); ...
c#,fluent-nhibernate,expression,kendo-grid
Wouldn't this do the trick? MemberExpression member = Expression.Convert( Expression.Property(pe, item.Member), typeof(int); ConstantExpression value = Expression.Constant((int)item.Value); ...
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,fluent-nhibernate,automapping
there is no direct syntax to make the many-to-one relation the inverse one. There are some reasons for this: it is more natural and performs better, because the reference in the class (Parent) directly maps to the foreign key in the database since it needs to be consistent in memory...