Search Results

Search found 4565 results on 183 pages for 'nhibernate mapping'.

Page 9/183 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Local Entities with NHibernate

    - by Ricardo Peres
    You may know that Entity Framework Code First has a nice property called Local which lets you iterate through all the entities loaded by the current context (first level cache). This comes handy at times, so I decided to check if it would be difficult to have it on NHibernate. It turned out it is not, so here it is! Another nice addition to an NHibernate toolbox! public static class SessionExtensions { public static IEnumerable<T> Local<T>(this ISession session) { ISessionImplementor impl = session.GetSessionImplementation(); IPersistenceContext pc = impl.PersistenceContext; foreach (Object key in pc.EntityEntries.Keys) { if (key is T) { yield return ((T) key); } } } } //simple usage IEnumerable<Post> localPosts = session.Local<Post>(); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • NHibernate Pitfalls: Lazy Scalar Properties Must Be Auto

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports lazy properties not just for associations (many to one, one to one, one to many, many to many) but also for scalar properties. This allows, for example, only loading a potentially large BLOB or CLOB from the database if and when it is necessary, that is, when the property is actually accessed. In order for this to work, other than having to be declared virtual, the property can’t have an explicitly declared backing field, it must be an auto property: 1: public virtual String MyLongTextProperty 2: { 3: get; 4: set; 5: } 6:  7: public virtual Byte [] MyLongPictureProperty 8: { 9: get; 10: set; 11: } All lazy scalar properties are retrieved at the same time, when one of them is accessed.

    Read the article

  • Mapping self-table one-to-many using non-PK clolumns

    - by Harel Moshe
    Hey, i have a legacy DB to which a Person object is mapped, having a collection of family-members, like this: class Person { ... string Id; /* 9-digits string */ IList<Person> Family; ... } The PERSON table seems like: Id: CHAR(9), PK FamilyId: INT, NOT NULL and several other non-relevant columns. I'm trying to map the Family collection to the PERSON table using the FamilyId column, which is not the PK as mentioned above. So, i actually have a one-to-many which is self-table-referential. I'm getting an error saying 'Cast is not valid' when my mapping looks like this: ... <set name="Family" table="Person" lazy="false"> <key column="FamilyId" /> <one-to-many class="Person" /> </set> ... because obviously, the join NHibernate is trying to make is between the PK column, Id, and the 'secondary' column, FamilyId, instead of joining the FamilyId column to itself. Any ideas please?

    Read the article

  • Will the following NHibernate interface mapping work?

    - by Ben Aston
    I'd like to program against interfaces when working with NHibernate due to type dependency issues within the solution I am working with. SO questions such as this indicate it is possible. I have an ILocation interface and a concrete Location type. Will the following work? HBM mapping: <class name="ILocation" abstract="true" table="ILocation"> <id name="Id" type="System.Guid" unsaved-value="00000000-0000-0000-0000-000000000000"> <column name="LocationId" /> <generator class="guid" /> </id> <union-subclass table="Location" name="Location"> <property name="Name" type="System.String"/> </union-subclass> </class> Detached criteria usage using the interface: var criteria = DetachedCriteria.For<ILocation>().Add(Restrictions.Eq("Name", "blah")); var locations = criteria.GetExecutableCriteria(UoW.Session).List<ILocation>(); Are there any issues with not using the hilo ID generator and/or with this approach in general?

    Read the article

  • NHibernate mapping with two special cases

    - by brainimus
    I am using NHibernate to map a class to a database table. The Part table has an ID column (primary key) and a ParentPart column (along with a few others). class Part { public virtual long ID{ get; set; } public virtual Part ParentPart { get; set; } } The ParentPart is normally another valid part in the part table but I have two special cases. I have a case where the ParentPart column can be 0 (zero) and another case where it can be -1. Neither of these cases currently represent another valid Part object. I was thinking I could make 2 subclasses of Part (ZeroPart and NegativeOnePart) that would never persist. I want the zero and -1 values to be entered in the column but not persist the entire ZeroPart or NegativeOnePart objects. I am unsure how to map this (I'm using hbm files) or if this even the correct approach. How can I map this so that normal valid parts are persisted but I can also handle the special cases? As an aside: My current hbm file has the Part.ID's unsaved value as zero but I think I can just change this in the mapping to something different and default it in the class.

    Read the article

  • Map NHibernate entity to multiple tables based on parent

    - by Programming Hero
    I'm creating a domain model where entities often (but not always) have a member of type ActionLog. ActionLog is a simple class which allows for an audit trail of actions being performed on an instance. Each action is recorded as an ActionLogEntry instance. ActionLog is implemented (approximately) as follows: public class ActionLog { public IEnumerable<ActionLogEntry> Entries { get { return EntriesCollection; } } protected ICollection<ActionLogEntry> EntriesCollection { get; set; } public void AddAction(string action) { // Append to entries collection. } } What I would like is to re-use this class amongst my entities and have the entries map to different tables based on which class they are logged against. For example: public class Customer { public ActionLog Actions { get; protected set; } } public class Order { public ActionLog Actions { get; protected set; } } This design is suitable for me in the application, however I can't see a clear way to map this scenario to a database with NHibernate. I typically use Fluent NHibernate for my configuration, but I'm happy to accept answers in more general HBM xml.

    Read the article

  • Does NHibernate LINQ support ToLower() in Where() clauses?

    - by Daniel T.
    I have an entity and its mapping: public class Test { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual string Description { get; set; } } public class TestMap : EntityMap<Test> { public TestMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Description); } } I'm trying to run a query on it (to grab it out of the database): var keyword = "test" // this is coming in from the user keyword = keyword.ToLower(); // convert it to all lower-case var results = session.Linq<Test> .Where(x => x.Name.ToLower().Contains(keyword)); results.Count(); // execute the query However, whenever I run this query, I get the following exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index Am I right when I say that, currently, Linq to NHibernate does not support ToLower()? And if so, is there an alternative that allows me to search for a string in the middle of another string that Linq to NHibernate is compatible with? For example, if the user searches for kap, I need it to match Kapiolani, Makapuu, and Lapkap.

    Read the article

  • How can i ignore map property in NHibernate with setter

    - by Emilio Montes
    i need ignore map property with setter in NHibernate, because the relationship between entities is required. this is my simple model public class Person { public virtual Guid PersonId { get; set; } public virtual string FirstName { get; set; } public virtual string SecondName { get; set; } //this is the property that do not want to map public Credential Credential { get; set; } } public class Credential { public string CodeAccess { get; set; } public bool EsPremium { get; set; } } public sealed class PersonMap : ClassMapping<Person> { public PersonMap() { Table("Person"); Cache(x => x.Usage(CacheUsage.ReadWrite)); Id(x => x.Id, m => { m.Generator(Generators.GuidComb); m.Column("PersonId"); }); Property(x => x.FirstName, map => { map.NotNullable(true); map.Length(255); }); Property(x => x.SecondName, map => { map.NotNullable(true); map.Length(255); }); } } I know that if I leave the property Credential {get;} I was not going to take the map of NHibernate, but I need to set the value. Thanks in advance.

    Read the article

  • NHibernate IQueryable Collection as Property of Root

    - by Khalid Abuhakmeh
    Hello and thank you for taking the time to read this. I have a root object that has a property that is a collection. For example : I have a Shelf object that has Books. // now public class Shelf { public ICollection<Book> Books {get; set;} } // want public class Shelf { public IQueryable<Book> Books {get;set;} } What I want to accomplish is to return a collection that is IQueryable so that I can run paging and filtering off of the collection directly from the the parent. var shelf = shelfRepository.Get(1); var filtered = from book in shelf.Books where book.Name == "The Great Gatsby" select book; I want to have that query executed specifically by NHibernate and not a get all to load a whole collection and then parse it in memory (which is what currently happens when I use ICollection). The reasoning behind this is that my collection could be huge, tens of thousands of records, and a get all query could bash my database. I would like to do this implicitly so that when NHibernate sees and IQueryable on my class it knows what to do. I have looked at NHibernates Linq provider and currently I am making the decision to take large collections and split them into their own repository so that I can make explicit calls for filtering and paging. Linq To SQL offers something similar to what I'm talking about.

    Read the article

  • Fluent NHibernate Map to private/protected Field that has no exposing Property

    - by Jon Erickson
    I have the following Person and Gender classes (I don't really, but the example is simplified to get my point across), using NHibernate (Fluent NHibernate) I want to map the Database Column "GenderId" [INT] value to the protected int _genderId field in my Person class. How do I do this? FYI, the mappings and the domain objects are in separate assemblies. public class Person : Entity { protected int _genderId; public virtual int Id { get; private set; } public virtual string Name { get; private set; } public virtual Gender Gender { get { return Gender.FromId(_genderId); } } } public class Gender : EnumerationBase<Gender> { public static Gender Male = new Gender(1, "Male"); public static Gender Female = new Gender(2, "Female"); private static readonly Gender[] _genders = new[] { Male, Female }; private Gender(int id, string name) { Id = id; Name = name; } public int Id { get; private set; } public string Name { get; private set; } public static Gender FromId(int id) { return _genders.Where(x => x.Id == id).SingleOrDefault(); } }

    Read the article

  • nhibernate fluent repository pattern insert problem

    - by voam
    I am trying to use Fluent NHibernate and the repository pattern. I would like my business layer to not be knowledgeable of the data persistence layer. Ideally I would pass in an initialized domain object to the insert method of the repository and all would be well. Where I run into problems is if the object being passed in has a child object. For example say I want to insert an a new order for a customer, and the customer is a property of the order object. I would like to do something like this: Customer c = new Customer; c.CustomerId = 1; Order o = new Order; o.Customer = c; repository.InsertOrder(o); The problem is that using NHiberate the CustomerId field is only privately settable so I can not set it directly like this. so what I have ended up doing is have my repository have an interface of Order InsertOrder(int customerId) where all the foreign keys get passed in as parameters. Somehow this just doesn't seem right. The other approach was to use the NHibernate session variable to load a customer object in my business model and then have the order passed in to the repository but this defeats my persistence ignorance ideal. Should I throw this persistence ignorance out the window or am I missing something here? Thanks

    Read the article

  • Fluent / NHibernate Collections of the same class

    - by Charlie Brown
    I am new to NHibernate and I am having trouble mapping the following relationships within this class. public class Category : IAuditable { public virtual int Id { get; set; } public virtual string Name{ get; set; } public virtual Category ParentCategory { get; set; } public virtual IList<Category> SubCategories { get; set; } public Category() { this.Name = string.Empty; this.SubCategories = new List<Category>(); } } Class Maps (although, these are practically guesses) public class CategoryMap : ClassMap<Category> { public CategoryMap() { Id(x => x.Id); Map(x => x.Name); References(x => x.ParentCategory) .Nullable() .Not.LazyLoad(); HasMany(x => x.SubCategories) .Cascade.All(); } } Each Category may have a parent category, some Categories have many subCategories, etc, etc I can get the Category to Save correctly (correct subcategories and parent category fk exist in the database) but when loading, it returns itself as the parent category. I am using Fluent for the class mapping, but if someone could point me in the right direction for just plain NHibernate that would work as well.

    Read the article

  • NHibernate.MappingException on table insertion.

    - by Suja
    The table structure is : The controller action to insert a row to table is public bool CreateInstnParts(string data) { IDictionary myInstnParts = DeserializeData(data); try { HSInstructionPart objInstnPartBO = new HSInstructionPart(); using (ISession session = Document.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { objInstnPartBO.DocumentId = Convert.ToInt32(myInstnParts["documentId"]); objInstnPartBO.InstructionId = Convert.ToInt32(myInstnParts["instructionId"]); objInstnPartBO.PartListId = Convert.ToInt32(myInstnParts["part"]); objInstnPartBO.PartQuantity = Convert.ToInt32(myInstnParts["quantity"]); objInstnPartBO.IncPick = Convert.ToBoolean(myInstnParts["incpick"]); objInstnPartBO.IsTracked = Convert.ToBoolean(myInstnParts["istracked"]); objInstnPartBO.UpdatedBy = User.Identity.Name; objInstnPartBO.UpdatedAt = DateTime.Now; session.Save(objInstnPartBO); transaction.Commit(); } return true; } } catch (Exception ex) { Console.Write(ex.Message); return false; } } This is throwing an exception NHibernate.MappingException was caught Message="No persister for: Hexsolve.Data.BusinessObjects.HSInstructionPart" Source="NHibernate" StackTrace: at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName) at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj) at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event) at NHibernate.Impl.SessionImpl.Save(Object obj) at HexsolveMVC.Controllers.InstructionController.CreateInstnParts(String data) in F:\Project\HexsolveMVC\Controllers\InstructionController.cs:line 1342 InnerException: Can anyone help me solve this??

    Read the article

  • NHibernate class referencing discriminator based subclass

    - by Rich
    I have a generic class Lookup which contains code/value properties. The table PK is category/code. There are subclasses for each category of lookup, and I've set the discriminator column in the base class and its value in the subclass. See example below (only key pieces shown): public class Lookup { public string Category; public string Code; public string Description; } public class LookupClassMap { CompositeId() .KeyProperty(x = x.Category, "CATEGORY_ID") .KeyProperty(x = x.Code, "CODE_ID"); DiscriminateSubclassesBasedOnColumn("CATEGORY_ID"); } public class MaritalStatus: Lookup {} public class MartialStatusClassMap: SubclassMap { DiscriminatorValue(13); } This all works. Here's the problem. When a class has a property of type MaritalStatus, I create a reference based on the contained code ID column ("MARITAL_STATUS_CODE_ID"). NHibernate doesn't like it because I didn't map both primary key columns (Category ID & Code ID). But with the Reference being of type MaritalStatus, NHibernate should already know what the value of the category ID is going to be, because of the discriminator value. What am I missing?

    Read the article

  • NHibernate with string primary key and relationships

    - by John_
    I've have just been stumped with this problem for an hour and I annoyingly found the problem eventually. THE CIRCUMSTANCES I have a table which users a string as a primary key, this table has various many to one and many to many relationships all off this primary key. When searching for multiple items from the table all relationships were brought back. However whenever I tried to get the object by the primary key (string) it was not bringing back any relationships, they were always set to 0. THE PARTIAL SOLUTION So I looked into my logs to see what the SQL was doing and that was returning the correct results. So I tried various things in all sorts of random ways and eventually worked out it was. The case of the string being passed into the get method was not EXACTLY the same case as it was in the database, so when it tried to match up the relationship items with the main entity it was finding nothing (Or at least NHIbernate wasn't because as I stated above the SQL was actually returning the correct results) THE REAL SOLUTION Has anyone else come across this? If so how do you tell NHibernate to ignore case when matching SQL results to the entity? It is silly because it worked perfectly well before now all of a sudden it has started to pay attention to the case of the string.

    Read the article

  • Many-to-Many Relationship mapping does not trigger the EventListener OnPostInsert or OnPostDelete Ev

    - by san
    I'm doing my auditing using the Events listeners that nHibernate provides. It works fine for all mappings apart from HasmanyToMany mapping. My Mappings are as such: Table("Order"); Id(x => x.Id, "OrderId"); Map(x => x.Name, "OrderName").Length(150).Not.Nullable(); Map(x => x.Description, "OrderDescription").Length(800).Not.Nullable(); Map(x => x.CreatedOn).Not.Nullable(); Map(x => x.CreatedBy).Length(70).Not.Nullable(); Map(x => x.UpdatedOn).Not.Nullable(); Map(x => x.UpdatedBy).Length(70).Not.Nullable(); HasManyToMany(x => x.Products) .Table("OrderProduct") .ParentKeyColumn("OrderId") .ChildKeyColumn("ProductId") .Cascade.None() .Inverse() .AsSet(); Table("Product"); Id(x => x.Id, "ProductId"); Map(x => x.ProductName).Length(150).Not.Nullable(); Map(x => x.ProductnDescription).Length(800).Not.Nullable(); Map(x => x.Amount).Not.Nullable(); Map(x => x.CreatedOn).Not.Nullable(); ; Map(x => x.CreatedBy).Length(70).Not.Nullable(); Map(x => x.UpdatedOn).Not.Nullable(); Map(x => x.UpdatedBy).Length(70).Not.Nullable(); HasManyToMany(x => x.Orders) .Table("OrderProduct") .ParentKeyColumn("ProductId") .ChildKeyColumn("OrderId") .Cascade.None() .AsSet(); Whenever I do an update of an order (Eg: Changed the Orderdescription and deleted one of the products associated with it) It works fine as in it updated the order table and deletes the row in the orderproduct table. the event listener that I have associated with it captures the update of the order table but does NOT capture the associated delete event when the orderproduct is deleted. This behaviour is observed only in case of a ManyTomany mapped relationships. Since I would also like audit the packageproduct deletion, its kind of an annoyance when the event listener aren't able to capture the delete event. Any information about it would be greatly appreciated.

    Read the article

  • NHibernate complex one-to-one mapping

    - by Eugene Strizhok
    There is a table A containing common unversioned data for entities. There are also tables B,C,D with versioned data of particular entity type. All of these tables are referencing table A. The task is to add a mapping of a property of entity's type, for example, stored in table B, which would reference table A, and specify a rule how entity should be fetch from table B based on identifier from table A. (For example, to fetch latest version of an entity). It it possible with NHibernate?

    Read the article

  • S#harp architecture mapping many to many and ado.net data services: A single resource was expected f

    - by Leg10n
    Hi, I'm developing an application that reads data from a SQL server database (migrated from a legacy DB) with nHibernate and s#arp architecture through ADO.NET Data services. I'm trying to map a many-to-many relationship. I have a Error class: public class Error { public virtual int ERROR_ID { get; set; } public virtual string ERROR_CODE { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<ErrorGroup> GROUPS { get; protected set; } } And then I have the error group class: public class ErrorGroup { public virtual int ERROR_GROUP_ID {get; set;} public virtual string ERROR_GROUP_NAME { get; set; } public virtual string DESCRIPTION { get; set; } public virtual IList<Error> ERRORS { get; protected set; } } And the overrides: public class ErrorGroupOverride : IAutoMappingOverride<ErrorGroup> { public void Override(AutoMapping<ErrorGroup> mapping) { mapping.Table("ERROR_GROUP"); mapping.Id(x => x.ERROR_GROUP_ID, "ERROR_GROUP_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<Error>(x => x.Error) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_GROUP_ID") .ChildKeyColumn("ERROR_ID").Inverse().AsBag(); } } public class ErrorOverride : IAutoMappingOverride<Error> { public void Override(AutoMapping<Error> mapping) { mapping.Table("ERROR"); mapping.Id(x => x.ERROR_ID, "ERROR_ID"); mapping.IgnoreProperty(x => x.Id); mapping.HasManyToMany<ErrorGroup>(x => x.GROUPS) .Table("ERROR_GROUP_LINK") .ParentKeyColumn("ERROR_ID") .ChildKeyColumn("ERROR_GROUP_ID").AsBag(); } } When I view the Data service in the browser like: http://localhost:1905/DataService.svc/Errors it shows the list of errors with no problems, and using it like http://localhost:1905/DataService.svc/Errors(123) works too. The Problem When I want to see the Errors in a group or the groups form an error, like: "http://localhost:1905/DataService.svc/Errors(123)?$expand=GROUPS" I get the XML Document, but the browser says: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. -------------------------------------------------------------------------------- Only one top level element is allowed in an XML document. Error processing resource 'http://localhost:1905/DataServic... <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> -^ I view the sourcecode, and I get the data. However it comes with an exception: <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code></code> <message xml:lang="en-US">An error occurred while processing this request.</message> <innererror xmlns="xmlns"> <message>A single resource was expected for the result, but multiple resources were found.</message> <type>System.InvalidOperationException</type> <stacktrace> at System.Data.Services.Serializers.Serializer.WriteRequest(IEnumerator queryResults, Boolean hasMoved)&#xD; at System.Data.Services.ResponseBodyWriter.Write(Stream stream)</stacktrace> </innererror> </error> A I missing something??? Where does this error come from?

    Read the article

  • Fluent NHibernate Many to one mapping

    - by Jit
    I am new to Hibernate world. It may be a silly question, but I am not able to solve it. I am testing many to One relationship of tables and trying to insert record. I have a Department table and Employee table. Employee and Dept has many to One relationship here. I am using Fluent NHibernate to add records. All codes below. Pls help - SQL Code create table Dept ( Id int primary key identity, DeptName varchar(20), DeptLocation varchar(20)) create table Employee ( Id int primary key identity, EmpName varchar(20),EmpAge int, DeptId int references Dept(Id)) Class Files public partial class Dept { public virtual System.String DeptLocation { get; set; } public virtual System.String DeptName { get; set; } public virtual System.Int32 Id { get; private set; } public virtual IList<Employee> Employees { get; set; } } public partial class Employee { public virtual System.Int32 DeptId { get; set; } public virtual System.Int32 EmpAge { get; set; } public virtual System.String EmpName { get; set; } public virtual System.Int32 Id { get; private set; } public virtual Project.Model.Dept Dept { get; set; } } Mapping Files public class DeptMapping : ClassMap { public DeptMapping() { Id(x = x.Id); Map(x = x.DeptName); Map(x = x.DeptLocation); HasMany(x = x.Employees) .Inverse() .Cascade.All(); } } public class EmployeeMapping : ClassMap { public EmployeeMapping() { Id(x = x.Id); Map(x = x.EmpName); Map(x = x.EmpAge); Map(x = x.DeptId); References(x = x.Dept) .Cascade.None(); } } My Code to add try { Dept dept = new Dept(); dept.DeptLocation = "Austin"; dept.DeptName = "Store"; Employee emp = new Employee(); emp.EmpName = "Ron"; emp.EmpAge = 30; IList<Employee> empList = new List<Employee>(); empList.Add(emp); dept.Employees = empList; emp.Dept = dept; IRepository<Dept> rDept = new Repository<Dept>(); rDept.SaveOrUpdate(dept); } catch (Exception ex) { Console.WriteLine(ex.Message); } Here i am getting error as InnerException = {"Invalid column name 'Dept_id'."} Message = "could not insert: [Project.Model.Employee][SQL: INSERT INTO [Employee] (EmpName, EmpAge, DeptId, Dept_id) VALUES (?, ?, ?, ?); select SCOPE_IDENTITY()]"

    Read the article

  • Using nhibernate <loader> element with HQL queries

    - by Matt
    Hi All I'm attempting to use an HQL query in element to load an entity based on other entities. My class is as follows public class ParentOnly { public ParentOnly(){} public virtual int Id { get; set; } public virtual string ParentObjectName { get; set; } } and the mapping looks like this <class name="ParentOnly"> <id name="Id"> <generator class="identity" /> </id> <property name="ParentObjectName" /> <loader query-ref="parentonly"/> </class> <query name="parentonly" > select new ParentOnly() from SimpleParentObject as spo where spo.Id = :id </query> The class that I am attemping to map on top of is SimpleParentObject, which has its own mapping and can be loaded and saved without problems. When I call session.Get(id) the sql runs correctly against the SimpleParentObject table, and the a ParentOnly object is instantiated (as I can step through the constructer), but only a null comes back, rather than the instantiated ParentOnly object. I can do this succesfully using a instead of the HQL, but am trying to build this in a database independent fashion. Any thoughts on how to get the and elements to return a populated ParentOnly object...? Thanks Matt

    Read the article

  • Load collections eagerly in NHibernate using Criteria API

    - by Zuber
    I have an entity A which HasMany entities B and entities C. All entities A, B and C have some references x,y and z which should be loaded eagerly. I want to read from the database all entities A, and load the collections of B and C eagerly using criteria API. So far, I am able to fetch the references in 'A' eagerly. But when the collections are loaded, the references within them are lazily loaded. Here is how I do it AllEntities_A = _session.CreateCriteria(typeof(A)) .SetFetchMode("x", FetchMode.Eager) .SetFetchMode("y", FetchMode.Eager) .List<A>().AsQueryable(); The mapping of entity A using Fluent is as shown below. _B and _C are private ILists for B & C respectively in A. Id(c => c.SystemId); Version(c => c.Version); References(c => c.x).Cascade.All(); References(c => c.y).Cascade.All(); HasMany<B>(Reveal.Property<A>("_B")) .AsBag() .Cascade.AllDeleteOrphan() .Not.LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); HasMany<C>(Reveal.Property<A>("_C")) .AsBag() .Cascade.AllDeleteOrphan() .LazyLoad() .Inverse() .Cache.ReadWrite().IncludeAll(); I don't want to make changes to the mapping file, and would like to load the entire entity A eagerly. i.e. I should get a List of A's where there will be List of B's and C's whose reference properties will also be loaded eagerly

    Read the article

  • Fluent NHibernate - How to map the foreign key column as a property

    - by Steve
    I am sure this is a straightforward question but consider the following: I have a reference between company and sector as follows: public class Company { public Guid ID { get; set; } public Sector Sector { get; set; } public Guid SectorID { get; set; } } public class Sector { public Guid ID { get; set; } public string Name { get; set; } } Ok. What I want is the SectorID of the Company object to be populated after I go: (new Company()).Sector = new Sector() { Name="asdf" } and do a flush. The mapping I am using kindly creates an additional column in the database called Sector_Id in the Company table, but this is not available as a property on Company. I want the SectorID property to be filled. The mapping i am currently using in the CompanyMap is References(c = c.Sector).Cascade.All(); Does anyone have any ideas?

    Read the article

  • Mixing inheritance mapping strategies in NHibernate

    - by MylesRip
    I have a rather large inheritance hierarchy in which some of the subclasses add very little and others add quite a bit. I don't want to map the entire hierarchy using either "table per class hierarchy" or "table per subclass" due to the size and complexity of the hierarchy. Ideally I'd like to mix mapping strategies such that portions of the hierarchy where the subclasses add very little are combined into a common table a la "table per class hierarchy" and subclasses that add a lot are broken out into a separate table. Using this approach, I would expect to have 2 or 3 tables with very little wasted space instead of either 1 table with lots of fields that don't apply to most of the objects, or 20+ tables, several of which would have only a couple of columns. In the NHibernate Reference Documentation version 2.1.0, I found section 8.1.4 "Mixing table per class hierarchy with table per subclass". This approach switches strategies partway down the hierarchy by using: ... <subclass ...> <join ...> <property ...> ... </join> </subclass> ... This is great in theory. In practice, though, I found that the schema was too restrictive in what was allowed inside the "join" element for me to be able to accomplish what I needed. Here is the related part of the schema definition: <xs:element name="join"> <xs:complexType> <xs:sequence> <xs:element ref="subselect" minOccurs="0" /> <xs:element ref="comment" minOccurs="0" /> <xs:element ref="key" /> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element ref="property" /> <xs:element ref="many-to-one" /> <xs:element ref="component" /> <xs:element ref="dynamic-component" /> <xs:element ref="any" /> <xs:element ref="map" /> <xs:element ref="set" /> <xs:element ref="list" /> <xs:element ref="bag" /> <xs:element ref="idbag" /> <xs:element ref="array" /> <xs:element ref="primitive-array" /> </xs:choice> <xs:element ref="sql-insert" minOccurs="0" /> <xs:element ref="sql-update" minOccurs="0" /> <xs:element ref="sql-delete" minOccurs="0" /> </xs:sequence> <xs:attribute name="table" use="required" type="xs:string" /> <xs:attribute name="schema" type="xs:string" /> <xs:attribute name="catalog" type="xs:string" /> <xs:attribute name="subselect" type="xs:string" /> <xs:attribute name="fetch" default="join"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="join" /> <xs:enumeration value="select" /> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="inverse" default="false" type="xs:boolean"> </xs:attribute> <xs:attribute name="optional" default="false" type="xs:boolean"> </xs:attribute> </xs:complexType> </xs:element> As you can see, this allows the use of "property" child elements or "component" child elements, but not both. It also doesn't allow for "subclass" child elements to continue the hierarchy below the point at which the strategy was changed. Is there a way to accomplish this?

    Read the article

  • NHibernate Mapping problem

    - by Bernard Larouche
    My database is being driven by my NHibernate mapping files. I have a Category class that looks like the following : public class Category { public Category() : this("") { } public Category(string name) { Name = name; SubCategories = new List<Category>(); Products = new HashSet<Product>(); } public virtual int ID { get; set; } public virtual string Name { get; set; } public virtual string Description { get; set; } public virtual Category Parent { get; set; } public virtual bool IsDefault { get; set; } public virtual ICollection<Category> SubCategories { get; set; } public virtual ICollection<Product> Products { get; set; } and here is my Mapping file : <property name="Name" column="Name" type="string" not-null="true"/> <property name="IsDefault" column="IsDefault" type="boolean" not-null="true" /> <property name="Description" column="Description" type="string" not-null="true" /> <many-to-one name="Parent" column="ParentID"></many-to-one> <bag name="SubCategories" inverse="true"> <key column="ParentID"></key> <one-to-many class="Category"/> </bag> <set name="Products" table="Categories_Products"> <key column="CategoryId"></key> <many-to-many column="ProductId" class="Product"></many-to-many> </set> when I try to create the database I get the following error : failed: The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK9AD976763BF05E2A". The conflict occurred in database "CoderForTraders", table "dbo.Categories", column 'CategoryId'. The statement has been terminated. I looked on the net for some answers but found none. Thanks for your help

    Read the article

  • nHibernate persist IList<DayOfWeek>

    - by Charlie Brown
    Is it possible to persist an IList<DayOfWeek> using nHibernate? public class Vendor { public virtual IList<DayOfWeek> OrderDays { get; private set; } } If not, what are some common solutions; creating a class for OrderDays?, using an IList<string>?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >