Search Results

Search found 744 results on 30 pages for 'fluent'.

Page 5/30 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • fluent nhibernate - storing and retrieving three classes in/from one table

    - by Will I Am
    Noob question. I have this situation where I have these objects: class Address { string Street; string City; ... } class User { string UserID; Address BillingAddress; Address MailingAddress; ... } What is the proper way of storing this data using (fluent) nHibernate? I could use a separate Address table and create a reference, but they are 1:1 relationships so I don't really want to incur the overhead of a join. Ideally I would store this as a single flat record. So, my question is, what is the proper way of storing an instance of class 'User' in such a way that it stores its contents and also the two addresses as a single record? My knowledge is failing me on how I can store this information in such a way that the two Address records get different column names (e.g. BillingAddress_Street and MailingAddress_Street, for example), and also how to read a record back into a User instance.

    Read the article

  • One-to-one Mapping issue with NHibernate/Fluent: Foreign Key not updateing

    - by Trevor
    Summary: Parent and Child class. One to one relationship between the Parent and Child. Parent has a FK property which references the primary key of the Child. Code as follows: public class NHTestParent { public virtual Guid NHTestParentId { get; set; } public virtual Guid ChildId { get { return ChildRef.NHTestChildId; } set { } } public virtual string ParentName { get; set; } protected NHTestChild _childRef; public virtual NHTestChild ChildRef { get { if (_childRef == null) _childRef = new NHTestChild(); return _childRef; } set { _childRef = value; } } } public class NHTestChild { public virtual Guid NHTestChildId { get; set; } public virtual string ChildName { get; set; } } With the following Fluent mappings: Parent Mapping Id(x => x.NHTestParentId); Map(x => x.ParentName); Map(x => x.ChildId); References(x => x.ChildRef, "ChildId").Cascade.All(); Child Mapping: Id(x => x.NHTestChildId); Map(x => x.ChildName); If I do something like (pseudo code) ... HTestParent parent = new NHTestParent(); parent.ParentName = "Parent 1"; parent.ChildRef.ChildName = "Child 1"; nhibernateSession.SaveOrUpdate(aParent); Commit; ... I get an error: "Invalid index 3 for this SqlParameterCollection with Count=3" If I change the parent 'References' line as follows (i.e. provide the name of the child property I'm pointing at): References(x => x.ChildRef, "ChildId").PropertyRef("NHTestChildId").Cascade.All(); I get the error: "Unable to resolve property: NHTestChildId" So, I tried the 'HasOne()' reference setting, as follows: HasOne<NHTestChild>(x => x.ChildRef).ForeignKey("ChildId").Cascade.All().Fetch.Join(); This results in the save working, but the load fails to find the child. If I inspect the SQL Nhibernate produces I can see that NHibernate is assuming the Primary key of the parent is the link to the child (i.e. load join condition is "parent.NHTestParentId = child.NHTestChildId). The 'ForeignKey' specified appears to be ignored. I can set any value and no error occurs - the join just always fails and no child is returned. I've tried a number of slight variations on the above. It seems like it should be a simple thing to achieve. Any ideas?

    Read the article

  • Fluent NHibernate - How to map a non nullable foreign key that exists in two joined tables

    - by vakman
    I'm mapping a set of membership classes for my application using Fluent NHibernate. I'm mapping the classes to the asp.net membership database structure. The database schema relevant to the problem looks like this: ASPNET_USERS UserId PK ApplicationId FK NOT NULL other user columns ... ASPNET_MEMBERSHIP UserId PK,FK ApplicationID FK NOT NULL other membership columns... There is a one to one relationship between these two tables. I'm attempting to join the two tables together and map data from both tables to a single 'User' entity which looks like this: public class User { public virtual Guid Id { get; set; } public virtual Guid ApplicationId { get; set; } // other properties to be mapped from aspnetuser/membership tables ... My mapping file is as follows: public class UserMap : ClassMap<User> { public UserMap() { Table("aspnet_Users"); Id(user => user.Id).Column("UserId").GeneratedBy.GuidComb(); Map(user => user.ApplicationId); // other user mappings Join("aspnet_Membership", join => { join.KeyColumn("UserId"); join.Map(user => user.ApplicationId); // Map other things from membership to 'User' class } } } If I try to run with the code above I get a FluentConfiguration exception Tried to add property 'ApplicationId' when already added. If I remove the line "Map(user = user.ApplicationId);" or change it to "Map(user = user.ApplicationId).Not.Update().Not.Insert();" then the application runs but I get the following exception when trying to insert a new user: Cannot insert the value NULL into column 'ApplicationId', table 'ASPNETUsers_Dev.dbo.aspnet_Users'; column does not allow nulls. INSERT fails. The statement has been terminated. And if I leave the .Map(user = user.ApplicationId) as it originally was and make either of those changes to the join.Map(user = user.ApplicationId) then I get the same exception above except of course the exception is related to an insert into the aspnet_Membership table So... how do I do this kind of mapping assuming I can't change my database schema?

    Read the article

  • fluent nhibernate one to many mapping

    - by Sammy
    I am trying to figure out what I thought was just a simple one to many mapping using fluent Nhibernate. I hoping someone can point me to the right directory to achieve this one to many relations I have an articles table and a categories table Many Articles can only belong to one Category Now my Categores table has 4 Categories and Articles has one article associated with cateory1 here is my setup. using FluentNHibernate.Mapping; using System.Collections; using System.Collections.Generic; namespace FluentMapping { public class Article { public virtual int Id { get; private set; } public virtual string Title { get; set; } public virtual Category Category{get;set;} } public class Category { public virtual int Id { get; private set; } public virtual string Description { get; set; } public virtual IList<Article> Articles { get; set; } public Category() { Articles=new List<Article>(); } public virtual void AddArticle(Article article) { article.Category = this; Articles.Add(article); } public virtual void RemoveArticle(Article article) { Articles.Remove(article); } } public class ArticleMap:ClassMap<Article> { public ArticleMap() { Table("Articles"); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Title); References(x => x.Category).Column("CategoryId").LazyLoad(); } public class CategoryMap:ClassMap<Category> { public CategoryMap() { Table("Categories"); Id(x => x.Id).GeneratedBy.Identity(); Map(x => x.Description); HasMany(x => x.Articles).KeyColumn("CategoryId").Fetch.Join(); } } } } if I run this test [Fact] public void Can_Get_Categories() { using (var session = SessionManager.Instance.Current) { using (var transaction = session.BeginTransaction()) { var categories = session.CreateCriteria(typeof(Category)) //.CreateCriteria("Articles").Add(NHibernate.Criterion.Restrictions.EqProperty("Category", "Id")) .AddOrder(Order.Asc("Description")) .List<Category>(); } } } I am getting 7 Categories due to Left outer join used by Nhibernate any idea what I am doing wrong in here? Thanks [Solution] After a couple of hours reading nhibernate docs I here is what I came up with var criteria = session.CreateCriteria(typeof (Category)); criteria.AddOrder(Order.Asc("Description")); criteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); var cats1 = criteria.List<Category>(); Using Nhibernate linq provider var linq = session.Linq<Category>(); linq.QueryOptions.RegisterCustomAction(c => c.SetResultTransformer(new DistinctRootEntityResultTransformer())); var cats2 = linq.ToList();

    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

  • Fluent NHibernate - subclasses with shared reference

    - by ollie
    Edit: changed class names. I'm using Fluent NHibernate (v 1.0.0.614) automapping on the following set of classes (where Entity is the base class provided in the S#arp Architecture framework): public class Car : Entity { public virtual int ModelYear { get; set; } public virtual Company Manufacturer { get; set; } } public class Sedan : Car { public virtual bool WonSedanOfYear { get; set; } } public class Company : Entity { public virtual IList<Sedan> Sedans { get; set; } } This results in the following Configuration (as written to hbm.xml): <class name="Company" table="Companies"> <id name="Id" type="System.Int32" unsaved-value="0"> <column name="`ID`" /> <generator class="identity" /> </id> <bag cascade="all" inverse="true" name="Sedans" mutable="true"> <key> <column name="`CompanyID`" /> </key> <one-to-many class="Sedan" /> </bag> </class> <class name="Car" table="Cars"> <id name="Id" type="System.Int32" unsaved-value="0"> <column name="`ID`" /> <generator class="identity" /> </id> <property name="ModelYear" type="System.Int32"> <column name="`ModelYear`" /> </property> <many-to-one cascade="save-update" class="Company" name="Manufacturer"> <column name="`CompanyID`" /> </many-to-one> <joined-subclass name="Sedan"> <key> <column name="`CarID`" /> </key> <property name="WonSedanOfYear" type="System.Boolean"> <column name="`WonSedanOfYear`" /> </property> </joined-subclass> </class> So far so good! But now comes the ugly part. The generated database tables: Table: Companies Columns: ID (PK, int, not null) Table: Cars Columns: ID (PK, int, not null) ModelYear (int, null) CompanyID (FK, int, null) Table: Sedan Columns: CarID (PK, FK, int, not null) WonSedanOfYear (bit, null) CompanyID (FK, int, null) Instead of one FK for Company, I get two! How can I ensure I only get one FK for Company? Override the automapping? Put a convention in place? Or is this a bug? Your thoughts are appreciated.

    Read the article

  • Fluent NHibernate: mapping complex many-to-many (with additional columns) and setting fetch

    - by HackedByChinese
    I need a Fluent NHibernate mapping that will fulfill the following (if nothing else, I'll also take the appropriate NHibernate XML mapping and reverse engineer it). DETAILS I have a many-to-many relationship between two entities: Parent and Child. That is accomplished by an additional table to store the identities of the Parent and Child. However, I also need to define two additional columns on that mapping that provide more information about the relationship. This is roughly how I've defined my types, at least the relevant parts (where Entity is some base type that provides an Id property and checks for equivalence based on that Id): public class Parent : Entity { public virtual IList<ParentChildRelationship> Children { get; protected set; } public virtual void AddChildRelationship(Child child, int customerId) { var relationship = new ParentChildRelationship { CustomerId = customerId, Parent = this, Child = child }; if (Children == null) Children = new List<ParentChildRelationship>(); if (Children.Contains(relationship)) return; relationship.Sequence = Children.Count; Children.Add(relationship); } } public class Child : Entity { // child doesn't care about its relationships } public class ParentChildRelationship { public int CustomerId { get; set; } public Parent Parent { get; set; } public Child Child { get; set; } public int Sequence { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var other = obj as ParentChildRelationship; if (return other == null) return false; return (CustomerId == other.CustomerId && Parent == other.Parent && Child == other.Child); } public override int GetHashCode() { unchecked { int result = CustomerId; result = Parent == null ? 0 : (result*397) ^ Parent.GetHashCode(); result = Child == null ? 0 : (result*397) ^ Child.GetHashCode(); return result; } } } The tables in the database look approximately like (assume primary/foreign keys and forgive syntax): create table Parent ( id int identity(1,1) not null ) create table Child ( id int identity(1,1) not null ) create table ParentChildRelationship ( customerId int not null, parent_id int not null, child_id int not null, sequence int not null ) I'm OK with Parent.Children being a lazy loaded property. However, the ParentChildRelationship should eager load ParentChildRelationship.Child. Furthermore, I want to use a Join when I eager load. The SQL, when accessing Parent.Children, NHibernate should generate an equivalent query to: SELECT * FROM ParentChildRelationship rel LEFT OUTER JOIN Child ch ON rel.child_id = ch.id WHERE parent_id = ? OK, so to do that I have mappings that look like this: ParentMap : ClassMap<Parent> { public ParentMap() { Table("Parent"); Id(c => c.Id).GeneratedBy.Identity(); HasMany(c => c.Children).KeyColumn("parent_id"); } } ChildMap : ClassMap<Child> { public ChildMap() { Table("Child"); Id(c => c.Id).GeneratedBy.Identity(); } } ParentChildRelationshipMap : ClassMap<ParentChildRelationship> { public ParentChildRelationshipMap() { Table("ParentChildRelationship"); CompositeId() .KeyProperty(c => c.CustomerId, "customerId") .KeyReference(c => c.Parent, "parent_id") .KeyReference(c => c.Child, "child_id"); Map(c => c.Sequence).Not.Nullable(); } } So, in my test if i try to get myParentRepo.Get(1).Children, it does in fact get me all the relationships and, as I access them from the relationship, the Child objects (for example, I can grab them all by doing parent.Children.Select(r => r.Child).ToList()). However, the SQL that NHibernate is generating is inefficient. When I access parent.Children, NHIbernate does a SELECT * FROM ParentChildRelationship WHERE parent_id = 1 and then a SELECT * FROM Child WHERE id = ? for each child in each relationship. I understand why NHibernate is doing this, but I can't figure out how to set up the mapping to make NHibernate query the way I mentioned above.

    Read the article

  • Fluent NHibernate/SQL Server 2008 insert query problem

    - by Mark
    Hi all, I'm new to Fluent NHibernate and I'm running into a problem. I have a mapping defined as follows: public PersonMapping() { Id(p => p.Id).GeneratedBy.HiLo("1000"); Map(p => p.FirstName).Not.Nullable().Length(50); Map(p => p.MiddleInitial).Nullable().Length(1); Map(p => p.LastName).Not.Nullable().Length(50); Map(p => p.Suffix).Nullable().Length(3); Map(p => p.SSN).Nullable().Length(11); Map(p => p.BirthDate).Nullable(); Map(p => p.CellPhone).Nullable().Length(12); Map(p => p.HomePhone).Nullable().Length(12); Map(p => p.WorkPhone).Nullable().Length(12); Map(p => p.OtherPhone).Nullable().Length(12); Map(p => p.EmailAddress).Nullable().Length(50); Map(p => p.DriversLicenseNumber).Nullable().Length(50); Component<Address>(p => p.CurrentAddress, m => { m.Map(p => p.Line1, "Line1").Length(50); m.Map(p => p.Line2, "Line2").Length(50); m.Map(p => p.City, "City").Length(50); m.Map(p => p.State, "State").Length(50); m.Map(p => p.Zip, "Zip").Length(2); }); Map(p => p.EyeColor).Nullable().Length(3); Map(p => p.HairColor).Nullable().Length(3); Map(p => p.Gender).Nullable().Length(1); Map(p => p.Height).Nullable(); Map(p => p.Weight).Nullable(); Map(p => p.Race).Nullable().Length(1); Map(p => p.SkinTone).Nullable().Length(3); HasMany(p => p.PriorAddresses).Cascade.All(); } public PreviousAddressMapping() { Table("PriorAddress"); Id(p => p.Id).GeneratedBy.HiLo("1000"); Map(p => p.EndEffectiveDate).Not.Nullable(); Component<Address>(p => p.Address, m => { m.Map(p => p.Line1, "Line1").Length(50); m.Map(p => p.Line2, "Line2").Length(50); m.Map(p => p.City, "City").Length(50); m.Map(p => p.State, "State").Length(50); m.Map(p => p.Zip, "Zip").Length(2); }); } My test is [Test] public void can_correctly_map_Person_with_Addresses() { var myPerson = new Person("Jane", "", "Doe"); var priorAddresses = new[] { new PreviousAddress(ObjectMother.GetAddress1(), DateTime.Parse("05/13/2010")), new PreviousAddress(ObjectMother.GetAddress2(), DateTime.Parse("05/20/2010")) }; new PersistenceSpecification<Person>(Session) .CheckProperty(c => c.FirstName, myPerson.FirstName) .CheckProperty(c => c.LastName, myPerson.LastName) .CheckProperty(c => c.MiddleInitial, myPerson.MiddleInitial) .CheckList(c => c.PriorAddresses, priorAddresses) .VerifyTheMappings(); } GetAddress1() (yeah, horrible name) has Line2 == null The tables seem to be created correctly in sql server 2008, but the test fails with a SQLException "String or binary data would be truncated." When I grab the sql statement in SQL Profiler, I get exec sp_executesql N'INSERT INTO PriorAddress (Line1, Line2, City, State, Zip, EndEffectiveDate, Id) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6)',N'@p0 nvarchar(18),@p1 nvarchar(4000),@p2 nvarchar(10),@p3 nvarchar(2),@p4 nvarchar(5),@p5 datetime,@p6 int',@p0=N'6789 Somewhere Rd.',@p1=NULL,@p2=N'Hot Coffee',@p3=N'MS',@p4=N'09876',@p5='2010-05-13 00:00:00',@p6=1001 Notice the @p1 parameter is being set to nvarchar(4000) and being passed a NULL value. Why is it setting the parameter to nvarchar(4000)? How can I fix it? Thanks!

    Read the article

  • Fluent NHibernate View Mapping requires Id Column

    - by Matt
    Hi Trying to use FNH to map a view - FNH insists on having a Id property mapped. However not all of my views have a unique identifing column. I can get around this with XML mappings as I can just specify a <id type="int"> <generator class="increment"/> </id> at the top of the mapping. Is there any way to duplicate this in FNH...? TIA Matt

    Read the article

  • Fluent NHibernate Map Enum as Lookup Table

    - by Jaimal Chohan
    I have the following (simplified) public enum Level { Bronze, Silver, Gold } public class Member { public virtual Level MembershipLevel { get; set; } } public class MemberMap : ClassMap<Member> { Map(x => x.MembershipLevel); } This creates a table with a column called MembershipLevel with the value as the Enum string value. What I want is for the entire Enum to be created as a lookup table, with the Membe table referencing this with the integer value as the FK. Also, I want to do this without bas***izing my model. Any ideas? [And I want time machine] [With 2 cup holders]

    Read the article

  • Fluent NHibernate Mapping and Formulas/DatePart

    - by Alessandro Di Lello
    Hi There, i have a very simple table with a Datetime column and i have this mapping in my domain object. MyDate is the name of the datetime column in the DB. public virtual int Day { get; set; } public virtual int Month { get; set; } public virtual int Year { get; set; } public virtual int Hour { get; set; } public virtual int Minutes { get; set; } public virtual int Seconds { get;set; } public virtual int WeekNo { get; set; } Map(x => x.Day).Formula("DATEPART(day, Datetime)"); Map(x => x.Month).Formula("DATEPART(month, Datetime)"); Map(x => x.Year).Formula("DATEPART(year, Datetime)"); Map(x => x.Hour).Formula("DATEPART(hour, Datetime)"); Map(x => x.Minutes).Formula("DATEPART(minute, Datetime)"); Map(x => x.Seconds).Formula("DATEPART(second, Datetime)"); Map(x => x.WeekNo).Formula("DATEPART(week, Datetime)"); This is working all great .... but Week Datepart. I saw with NHProf the sql generating for a select and here's the problem it's generating all the sql correctly but for week datepart.. this is part of the SQL generated: ....Datepart(day, MyDate) ... ....Datepart(month, MyDate) ... ....Datepart(year, MyDate) ... ....Datepart(hour, MyDate) ... ....Datepart(minute, MyDate) ... ....Datepart(second, MyDate) ... ....Datepart(this_.week, MyDate) ... where this_ is the alias for the table that nhibernate uses. so it's treating the week keyword for the datepart stuff as a column or something like that. To clarify there's no column or properties that is called week. some help ? cheers Alessandro

    Read the article

  • Fluent NHibernate Automapping with RIA services

    - by VexXtreme
    Hi guys I've encountered a slight problem recently, or rather a lack of understanding of how NHibernate automapping works with RIA data services. Namely, I don't understand how to use Association and Include attributes. For instance, I've created two tables in my database and corresponding classes (that NHibernate correctly fills). The problem is, RIA doesn't generate properties (collections) bound by foreign key to other tables, on the client side, although I've defined them in my classes in my domain model... it generates just properties that belong to their own class, on the client side. I assume that these attributes aren't necessary since NHibernate automapper is supposed to fill those collections on it's own... I'm quite confused as to how this works. And I don't understand why RIA simply skips properties such as public virtual IList<Medication> Medications{ get; set; } during autogeneration. Any input is appreciated Thanks

    Read the article

  • NHibernate L2 Cache - fluent nHibernate configuration

    - by AWC
    I've managed to configure the L2 cache for Get\Load in FHN, but it's not working for queries configured using the ICriteria interface - it doesn't cache the results from these queries. Does anyone know why? The configurations are as follows: ICriteria: return unitOfWork .CurrentSession .CreateCriteria(typeof(Country)) .SetCacheable(true); Entity Mapping: public sealed class CountryMap : ClassMap<Country>, IMap { public CountryMap() { Table("Countries"); Not.LazyLoad(); Cache.ReadWrite().IncludeAll(); Id(x => x.Id); Map(x => x.TwoLetter); Map(x => x.ThreeLetter); Map(x => x.Name); } } And the session factory configuration for the database property: return () => MsSqlConfiguration.MsSql2005 .ConnectionString(BuildConnectionString()) .ShowSql() .Cache(c => c.UseQueryCache() .QueryCacheFactory<StandardQueryCacheFactory>() .ProviderClass(configuration.RepositoryCacheType) .UseMinimalPuts()) .FormatSql() .UseReflectionOptimizer(); Cheers AWC

    Read the article

  • Fluent NHibernate and PostgreSQL, SchemaMetadataUpdater.QuoteTableAndColumns - System.NotSupportedEx

    - by Vyacheslav
    Hello! I'm using fluentnhibernate with PostgreSQL. Fluentnhibernate is last version. PosrgreSQL version is 8.4. My code for create ISessionFactory: public static ISessionFactory CreateSessionFactory() { string connectionString = ConfigurationManager.ConnectionStrings["PostgreConnectionString"].ConnectionString; IPersistenceConfigurer config = PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString); FluentConfiguration configuration = Fluently .Configure() .Database(config) .Mappings(m => m.FluentMappings.Add(typeof(ResourceMap)) .Add(typeof(TaskMap)) .Add(typeof(PluginMap))); var nhibConfig = configuration.BuildConfiguration(); SchemaMetadataUpdater.QuoteTableAndColumns(nhibConfig); return configuration.BuildSessionFactory(); } When I'm execute code at line SchemaMetadataUpdater.QuoteTableAndColumns(nhibConfig); throw error: System.NotSupportedException: Specified method is not supported. Help me, please! I'm very need for solution. Best regards

    Read the article

  • Fluent Nhibernate - Mapping two entities to same table

    - by Andy
    Hi, I'm trying to map two domain entities to the same table. We're doing a smart entity for our domain model, so we have the concept of an Editable Address and a readonly Address. I have both mapped using Classmaps, and everything seems to go fine until we try to export the schema using the SchemaExport class from NHibernate. It errors out saying the table already exists. I assume it's something simple that I'm just not seeing. Any ideas? Thanks

    Read the article

  • Fluent nhibernate: Enum in composite key gets mapped to int when I need string

    - by Quintin Par
    By default the behaviour of FNH is to map enums to its string in the db. But while mapping an enum as part of a composite key, the property gets mapped as int. e.g. in this case public class Address : Entity { public Address() { } public virtual AddressType Type { get; set; } public virtual User User { get; set; } Where AddresType is of public enum AddressType { PRESENT, COMPANY, PERMANENT } The FNH mapping is as mapping.CompositeId().KeyReference(x => x.User, "user_id").KeyProperty(x => x.Type); the schema creation of this mapping results in create table address ( Type INTEGER not null, user_id VARCHAR(25) not null, and the hbm as <composite-id mapped="true" unsaved-value="undefined"> <key-property name="Type" type="Company.Core.AddressType, Company.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <column name="Type" /> </key-property> <key-many-to-one name="User" class="Company.Core.CompanyUser, Company.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <column name="user_id" /> </key-many-to-one> </composite-id> Where the AddressType should have be generated as type="FluentNHibernate.Mapping.GenericEnumMapper`1[[Company.Core.AddressType, How do I instruct FNH to mappit as the default string enum generic mapper?

    Read the article

  • (Fluent)NHibernate: Mapping an IDictionary<MappedClass, MyEnum>

    - by anthony
    I've found a number of posts about this but none seem to help me directly. Also there seems to be confusion about solutions working or not working during different stages of FluentNHibernate's development. I have the following classes: public class MappedClass { ... } public enum MyEnum { One, Two } public class Foo { ... public virtual IDictionary<MappedClass, MyEnum> Values { get; set; } } My questions are: Will I need a separate (third) table of MyEnum? How can I map the MyEnum type? Should I? What should Foo's mapping look like? I've tried mapping HasMany(x = x.Values).AsMap("MappedClass")... This results in: NHibernate.MappingException : Association references unmapped class: MyEnum

    Read the article

  • Fluent interface design and code smell

    - by Jiho Han
    public class StepClause { public NamedStepClause Action1() {} public NamedStepClause Action2() {} } public class NamedStepClause : StepClause { public StepClause Step(string name) {} } Basically, I want to be able to do something like this: var workflow = new Workflow().Configure() .Action1() .Step("abc").Action2() .Action2() .Step("def").Action1(); So, some "steps" are named and some are not. The thing I do not like is that the StepClause has knowledge of its derived class NamedStepClause. I tried a couple of things to make this sit better with me. I tried to move things out to interfaces but then the problem just moved from the concrete to the interfaces - INamedStepClause still need to derive from IStepClause and IStepClause needs to return INamedStepClause to be able to call Step(). I could also make Step() part of a completely separate type. Then we do not have this problem and we'd have: var workflow = new Workflow().Configure() .Step().Action1() .Step("abc").Action2() .Step().Action2() .Step("def").Action1(); Which is ok but I'd like to make the step-naming optional if possible. I found this other post on SO here which looks interesting and promising. What are your opinions? I'd think the original solution is completely unacceptable or is it? By the way, those action methods will take predicates and functors and I don't think I want to take an additional parameter for naming the step there. The point of it all is, for me, is to only define these action methods in one place and one place only. So the solutions from the referenced link using generics and extension methods seem to be the best approaches so far.

    Read the article

  • fluent nhibernate select n+1 problem

    - by Andrew Bullock
    I have a fairly deep object graph (5-6 nodes), and as I traverse portions of it NHProf is telling me I've got a "Select N+1" problem (which I do). The two solutions I'm aware of are Eager load children Break apart my object graph (and eager load) I don't really want to do either of these (although I may break the graph apart later as I forsee it growing) For now.... Is it possible to tell NHibernate (with fluentnhib) that whenever i try to access children, to load them all in one go, instead of selectn+1ing as i iterate over them? I'm also getting "unbounded results set"s, which is presumably the same problem (or rather, will be solved by the above solution if possible). Each child collection (throughout the graph) will only ever have about 20 members, but 20^5 is a lot, so i dont want to eager load everything when i get the root, but simply get all of a child collection whenever i go near it Edit: an afterthought.... what if i want to introduce paging when i want to render children? do i HAVE to break my object graph here, or is there some sneakyness i can employ to solve all these issues?

    Read the article

  • (fluent) nhibernate conditional table mapping strategy

    - by grenade
    I have no control over database schema and have the following (simplified) table structure: CityProfile Id Name CountryProfile Id Name RegionProfile Id Name I have a .Net enum and class encapsulating the lot: public enum Scope { Region, Country, City } public class Profile { public Scope Scope { get; set; } public int Id { get; set; } public string Name { get; set; } } I am looking for a mechanism that allows me to map to the correct table, something like: public class ProfileMap : ClassMap<Profile> { public ProfileMap() { switch (x => x.Scope) { // <--Invalid code here! case Scope.City: Table("CityProfile"); break; case Scope.Country: Table("CountryProfile"); break; case Scope.Region: Table("RegionProfile"); break; } Id(x => x.Id); Map(x => x.Name); } } Or have I approached this wrong?

    Read the article

  • Fluent Nhibernate causes System.IndexOutOfRangeException on Commit()

    - by Moss
    Hey there. I have been trying to figure out how to configure the mapping with both NH and FluentNH for days, and I think I'm almost there, but not quite. I have the following problem. What I need to do is basically map these two entities, which are simplified versions of the actual ones. Airlines varchar2(3) airlineCode //PK varchar2(50) Aircraft varchar2(3) aircraftCode //composite PK varchar2(3) airlineCode //composite PK, FK referencing PK in Airlines varchar2(50) aircraftName My classes look like class Airline { string AirlineCode; string AirlineName; IList<Aircraft> Fleet; } class Aircraft { Airline Airline; string AircraftCode; string AircraftName; } Using FluentNH, I mapped it like so AirlineMap Table("Airlines"); Id(x => x.AirlineCode); Map(x => x.AirlineName); HasMany<Aircraft>(x => x.Fleet) .KeyColumn("Airline"); AircraftMap Table("Aircraft"); CompositeId() .KeyProperty(x => x.AircraftCode) .KeyReference(x => x.Airline); Map(x => x.AircraftName); References(x => x.Airline) .Column("Airline"); Using Nunit, I'm testing the addition of another aircraft, but upon calling transaction.Commit after session.Save(aircraft), I get an exception: "System.IndexOutOfRangeException : Invalid index 22 for this OracleParameterCollection with Count=22." The Aircraft class (and the table) has 22 properties. Anyone have any ideas?

    Read the article

  • Fluent NHibernate Self Referencing Many To Many

    - by Jeremy
    I have an entity called Books that can have a list of more books called RelatedBooks. The abbreviated Book entity looks something likes this: public class Book { public virtual long Id { get; private set; } public virtual IList<Book> RelatedBooks { get; set; } } Here is what the mapping looks like for this relationship HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks") .Cascade.SaveUpdate(); Here is a sample of the data that is then generated in the RelatedBooks table: BookId RelatedBookId 1 2 1 3 The problem happens when I Try to delete a book. If I delete the book that has an ID of 1, everything works ok and the RelatedBooks table has the two corresponding records removed. However if I try to delete the book with an ID of 3, I get the error "The DELETE statement conflicted with the REFERENCE constraint "FK5B54405174BAB605". The conflict occurred in database "Test", table "dbo.RelatedBooks", column 'RelatedBookId'". Basically what is happening is the Book cannot be deleted because the record in the RelatedBooks table that has a RelatedBookId of 3 is never deleted. How do I get that record to be deleted when I delete a book? EDIT After changing the Cascade from SaveUpdate() to All(), the same problem still exists if I try to delete the Book with an ID of 3. Also with Cascade set to All(), if delete the Book with and ID of 1, then all 3 books (ID's: 1, 2 and 3) are deleted so that won't work either. Looking at the SQL that is executed when the Book.Delete() method is called when I delete the Book with an ID of 3, it looks like the SELECT statement is looking at the wrong column (which I assume means that the SQL DELETE statment would make the same mistake, therefore never removing that record). Here is the SQL for the RelatedBook SELECT relatedboo0_.BookId as BookId3_ , relatedboo0_.RelatedBookId as RelatedB2_3_ , book1_.Id as Id14_0_ FROM RelatedBooks relatedboo0_ left outer join [Book] book1_ on relatedboo0_.RelatedBookId=book1_.Id WHERE relatedboo0_.BookId=3 The WHERE statment should look something like this for thie particular case: WHERE relatedboo0_.RelatedBookId = 3 SOLUTION Here is what I had to do to get it working for all cases Mapping: HasManyToMany(x => x.RelatedBooks) .ParentKeyColumn("BookId") .ChildKeyColumn("RelatedBookId") .Table("RelatedBooks"); Code: var book = currentSession.Get<Book>(bookId); if (book != null) { //Remove all of the Related Books book.RelatedBooks.Clear(); //Get all other books that have this book as a related book var booksWithRelated = currentSession.CreateCriteria<Book>() .CreateAlias("RelatedBooks", "br") .Add(Restrictions.Eq("br.Id", book.Id)) .List<Book>(); //Remove this book as a Related Book for all other Books foreach (var tempBook in booksWithRelated) { tempBook.RelatedBooks.Remove(book); tempBook.Save(); } //Delete the book book.Delete(); }

    Read the article

  • Inherited fluent nhibenate mapping issue

    - by Aim Kai
    I have an interesting issue today!! Basically I have two classes. public class A : B { public virtual new ISet<DifferentItem> Items {get;set;} } public class B { public virtual int Id {get;set;} public virtual ISet<Item> Items {get;set;} } The subclass A hides the base class B property, Items and replaces it with a new property with the same name and a different type. The mappings for these classes are public class AMapping : SubclassMap<A> { public AMapping() { HasMany(x=>x.Items) .LazyLoad() .AsSet(); } } public class BMapping : ClassMap<B> { public BMapping() { Id(x=>x.Id); HasMany(x=>x.Items) .LazyLoad() .AsSet(); } } However when I run my unit test to check the mapping I get the following exception: Tests the A mapping: NHibernate.PropertyAccessException : Invalid Cast (check your mapping for property type mismatches); setter of A ---- System.InvalidCastException : Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[Item]' to type 'Iesi.Collections.Generic.ISet1[DifferentItem]'. Anyone have any ideas? Clearly it is something to do with the type of the collection on the sub-class. But I skimmed through the available options on the mapping class and nothing stood out as being the solution here.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >