Search Results

Search found 1981 results on 80 pages for 'fluent nhibernate'.

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

  • FluentNHibernate mapping of composite foreign keys

    - by Faron
    I have an existing database schema and wish to replace the custom data access code with Fluent.NHibernate. The database schema cannot be changed since it already exists in a shipping product. And it is preferable if the domain objects did not change or only changed minimally. I am having trouble mapping one unusual schema construct illustrated with the following table structure: CREATE TABLE [Container] ( [ContainerId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_Container] PRIMARY KEY ( [ContainerId] ASC ) ) CREATE TABLE [Item] ( [ItemId] [uniqueidentifier] NOT NULL, [ContainerId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_Item] PRIMARY KEY ( [ContainerId] ASC, [ItemId] ASC ) ) CREATE TABLE [Property] ( [ContainerId] [uniqueidentifier] NOT NULL, [PropertyId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_Property] PRIMARY KEY ( [ContainerId] ASC, [PropertyId] ASC ) ) CREATE TABLE [Item_Property] ( [ContainerId] [uniqueidentifier] NOT NULL, [ItemId] [uniqueidentifier] NOT NULL, [PropertyId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_Item_Property] PRIMARY KEY ( [ContainerId] ASC, [ItemId] ASC, [PropertyId] ASC ) ) CREATE TABLE [Container_Property] ( [ContainerId] [uniqueidentifier] NOT NULL, [PropertyId] [uniqueidentifier] NOT NULL, CONSTRAINT [PK_Container_Property] PRIMARY KEY ( [ContainerId] ASC, [PropertyId] ASC ) ) The existing domain model has the following class structure: The Property class contains other members representing the property's name and value. The ContainerProperty and ItemProperty classes have no additional members. They exist only to identify the owner of the Property. The Container and Item classes have methods that return collections of ContainerProperty and ItemProperty respectively. Additionally, the Container class has a method that returns a collection of all of the Property objects in the object graph. My best guess is that this was either a convenience method or a legacy method that was never removed. The business logic mainly works with Item (as the aggregate root) and only works with a Container when adding or removing Items. I have tried several techniques for mapping this but none work so I won't include them here unless someone asks for them. How would you map this?

    Read the article

  • NHibernate One to One Foreign Key ON DELETE CASCADE

    - by xll
    I need to implement One-to-one association between Project and ProjecSettings using fluent NHibernate: public class ProjectMap : ClassMap<Project> { public ProjectMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<Project>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<Project>())) .Not.Nullable(); HasOne(x => x.ProjectSettings) .PropertyRef(x => x.Project); } } public class ProjectSettingsMap : ClassMap<ProjectSettings> { public ProjectSettingsMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<ProjectSettings>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<ProjectSettings>())); References(x => x.Project) .Column(MapUtils.Ref<ProjectSettings, Project>(p => p.Project, p => p.Id)) .Unique() .Not.Nullable(); } } This results in the following sql for Project Settings: CREATE TABLE ProjectSettings ( Id bigint PRIMARY KEY NOT NULL, Project_Project_Id bigint NOT NULL UNIQUE, /* Foreign keys */ FOREIGN KEY (Project_Project_Id) REFERENCES Project() ON DELETE NO ACTION ON UPDATE NO ACTION ); What I am trying to achieve is to have ON DELETE CASCADE for the FOREIGN KEY (Project_Project_Id), so that when the project is deleted through sql query, it's settings are deleted too. How can I achieve this ? EDIT: I know about Cascade.Delete() option, but it's not what I need. Is there any way to intercept the FK statement generation?

    Read the article

  • nhibernate fatal error

    - by Afif Lamloumi
    i have an error ( System.InvalidCastException: Unable to cast object of type 'AccountProxy' to type 'System.String'.) when i did this code i mapped the tables( Account,AccountString,EventData,...) of the the database opengts ( open source) i have this error when i called a function from EventData.cs IQuery query = session.CreateQuery("FROM Eventdata"); IList pets = query.List(); return pets; the Stack Trace: [InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'AccountProxy' en type 'System.String'.] (Object , Object[] , SetterCallback ) +431 NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) +20 NHibernate.Tuple.Component.PocoComponentTuplizer.SetPropertyValues(Object component, Object[] values) +49 NHibernate.Type.ComponentType.SetPropertyValues(Object component, Object[] values, EntityMode entityMode) +34 NHibernate.Type.ComponentType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) +150 NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +42 NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session) +93 NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +92 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +675 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +129 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +116 [GenericADOException: could not execute query [ select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_ ] [SQL: select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +213 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +79 NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +51 NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +231 NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369 NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +317 NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282 NHibernate.Impl.QueryImpl.List() +163 DATA1.EventdataExtensions.GetEventdata() in C:\Users\HP\Desktop\our_project\DATA1\Queries\Eventdata.cs:33 MvcApplication7.Controllers.HistoriqueController.Index() in C:\Users\HP\Desktop\our_project\MvcApplication7\Controllers\HistoriqueController.cs:17 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any suggestions? how can correct this error Data entity class (outtake from comment): public class MyClass { public virtual string DeviceID { get; set; } public virtual int Timestamp { get; set; } public virtual string Account { get; set; } public virtual int StatusCode { get; set; } public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } public virtual int GpsAge { get; set; } public virtual double SpeedKPH { get; set; } public virtual double Heading { get; set; } public override bool Equals(object obj) { return true; } public override int GetHashCode() { return 0; } }

    Read the article

  • What would be the equivalent VB.NET code for this C# FluentNHibernate component mapping?

    - by Will Marcouiller
    I'm a C# programmer constrained to write VB.NET code. While exploring NHibernate further for my current client, I encountered FluentNHibernate, which I find real attractive. But now, I wonder how to "translate" this C# code for component mapping into VB.NET code: Component(x => x.Address, m => { m.Map(x => x.Number); m.Map(x => x.Street); m.Map(x => x.PostCode); }); I know from here: Component(Of Client)(Function(c) c.Address, ...) what I miss is how to continue with the brackets in VB.NET, since there's no Begin End keywords or so. EDIT 1: Following Mr. JaredPar instructions, I figured that his solution might work. If we take the time to read his answer, we may notice that we both don't know what the MType is within his solution. I might have found out that the MType is: FluentNHibernate.Mapping.ComponentPart(Of TComponent) Thus, TComponent is, from my understanding, an anonymous type that I shall parameter to use. From this point of view, since I wish to map the properties of my Address object, replacing TComponent in my help method signature seems not to work. Private Sub MapAdresseHelper(Of Adresse)(ByVal a As FluentNHibernate.Mapping.ComponentPart(Of Adresse)) a.Map(Function(m) m.Number) a.Map(Function(m) m.Street).Length(50) a.Map(Function(m) m.PostCode).Length(10) End Sub The error I get is that my Address class doesn't have a property member named Street, for instance. It sees my Address type, it recognizes it, but it seems buggy somehow. I guess VBNET is poorly designed for lambda expressions and is less evolved than C# (Sorry, a bit of frustration due to the constraint of working with it and not being capable of doing things VERY easily done in C#.) Thanks!

    Read the article

  • Nhibernat mapping aspnet_Users table

    - by Michael D. Kirkpatrick
    My User table I want to map to aspnet_Users: <class name="User" table="`User`"> <id name="ID" column="ID" type="Int32" unsaved-value="0"> <generator class="native" /> </id> <property name="UserId" column="UserId" type="Guid" not-null="true" /> <property name="FullName" column="FullName" type="String" not-null="true" /> <property name="PhoneNumber" column="PhoneNumber" type="String" not-null="false" /> </class> My aspnet_Users table: <class name="aspnet_Users" table="aspnet_Users"> <id name="ID" column="UserId" type="Guid" /> <property name="UserName" column="UserName" type="string" not-null="false" /> </class> I tried adding one-to-one, one-to-many and many-to-one mappings. The closest I can get is with this error: Object of type 'System.Guid' cannot be converted to type 'System.Int32'. How do I create a 1 way mapping from User to aspnet_User via the UserId column in User? I am only wanting to create a reference so I can extract read-only information, affect sorts, etc. I still need to leave UserId column in User set up like it is now. Maybe a virtual reference keying off of UserId? Is this even possible with Nhibernate? Unfortunately it acts like it only wants to use ID from User to map to aspnet_Users. Changing the table User to have it's primary key be UserId instead of ID is not an option at this point. Any help would be greatly appreciated. Thanks in advance.

    Read the article

  • Specify Columntype in nhibernate

    - by Bipul
    I have a class CaptionItem public class CaptionItem { public virtual int SystemId { get; set; } public virtual int Version { get; set; } protected internal virtual IDictionary<string, string> CaptionValues {get; private set;} } I am using following code for nHibernate mapping Id(x => x.SystemId); Version(x => x.Version); Cache.ReadWrite().IncludeAll(); HasMany(x => x.CaptionValues) .KeyColumn("CaptionItem_Id") .AsMap<string>(idx => idx.Column("CaptionSet_Name"), elem => elem.Column("Text")) .Not.LazyLoad() .Cascade.Delete() .Table("CaptionValue") .Cache.ReadWrite().IncludeAll(); So in database two tables get created. One CaptionValue and other CaptionItem. In CaptionItem table has three columns 1. CaptionItem_Id int 2. Text nvarchar(255) 3. CaptionSet_Name nvarchar(255) Now, my question is how can I make the columnt type of Text to nvarchar(max)? Thanks in advance.

    Read the article

  • Problem with delete operation in many to many relation

    - by Alexey Zakharov
    Hi, I've got to classes Product and Store which have many to many relation I want deleting of store not to cause deleting of related product And deleting of product not to cause deleting of related store. Currently deleting of entity cause exception due to Foreign Key constraint. Here is this classes and their mapping in fluent hibernate: public class Product { public Product() { this.StoresStockedIn = new List<Store>(); } public virtual string Name { get; set; } public virtual double Price { get; set; } public virtual long ProductID { get; set; } public virtual IList<Store> StoresStockedIn { get; set; } } public class Store { public Store() { this.Products = new List<Product>(); this.Staff = new List<Employee>(); } public virtual string Name { get; set; } public virtual IList<Product> Products { get; set; } public virtual IList<Employee> Staff { get; set; } public virtual long StoreID { get; set; } } public class ProductMap : ClassMap<Product> { public ProductMap() { this.Id(x => x.ProductID); this.Map(x => x.Name); this.Map(x => x.Price); this.HasManyToMany(x => x.StoresStockedIn) .Cascade.None() .Table("StoreProduct"); } public class StoreMap : ClassMap<Store> { public StoreMap() { this.Id(x => x.StoreID); this.Map(x => x.Name); this.HasManyToMany(x => x.Products) .Cascade.None() .Inverse() .Table("StoreProduct"); this.HasMany(x => x.Staff) .Cascade.All() .Inverse(); } } Thanks, Alexey Zakharov

    Read the article

  • Fleunt NHibernate not working outside of nunit test fixtures

    - by thorkia
    Okay, here is my problem... I created a Data Layer using the RTM Fluent Nhibernate. My create session code looks like this: _session = Fluently.Configure(). Database(SQLiteConfiguration.Standard.UsingFile("Data.s3db")) .Mappings( m => { m.FluentMappings.AddFromAssemblyOf<ProductMap>(); m.FluentMappings.AddFromAssemblyOf<ProductLogMap>(); }) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); When I reference the module in a test project, then create a test fixture that looks something like this: [Test] public void CanAddProduct() { var product = new Product {Code = "9", Name = "Test 9"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); using (ISession session = OrmHelper.OpenSession()) { var fromDb = session.Get<Product>(product.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(fromDb, product); Assert.AreEqual(fromDb.Id, product.Id); } My tests pass. When I open up the created SQLite DB, the new Product with Code 9 is in it. the tables for Product and ProductLog are there. Now, when I create a new console application, and reference the same library, do something like this: Product product = new Product() {Code = "10", Name = "Hello"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); Console.WriteLine(product.Id); Console.ReadLine(); It doesn't work. I actually get pretty nasty exception chain. To save you lots of head aches, here is the summary: Top Level exception: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.\r\n\r\n The PotentialReasons collection is empty The Inner exception: The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use element in the application configuration file to specify the full name of the assembly. Both the unit test library and the console application reference the exact same version of System.Data.SQLite. Both projects have the exact same DLLs in the debug folder. I even tried copying SQLite DB the unit test library created into the debug directory of the console app, and removed the build schema lines and it still fails If anyone can help me figure out why this won't work outside of my unit tests it would be greatly appreciated. This crazy bug has me at a stand still.

    Read the article

  • nhibernate/fluenthibernate throws StackOverflowException

    - by Gianluca Colucci
    Hi there! In my project I am using NHibernate/FluentNHibernate, and I am working with two entities, contracts and services. This is my contract type: [Serializable] public partial class TTLCContract { public virtual long? Id { get; set; } // other properties here public virtual Iesi.Collections.Generic.ISet<TTLCService> Services { get; set; } // implementation of Equals // and GetHashCode here } and this is my service type: [Serializable] public partial class TTLCService { public virtual long? Id { get; set; } // other properties here public virtual Activity.Models.TTLCContract Contract { get; set; } // implementation of Equals // and GetHashCode here } Ok, so as you can see, I want my contract object to have many services, and each Service needs to have a reference to the parent Contract. I am using FluentNhibernate. So my mappings file are the following: public TTLCContractMapping() { Table("tab_tlc_contracts"); Id(x => x.Id, "tlc_contract_id"); HasMany(x => x.Services) .Inverse() .Cascade.All() .KeyColumn("tlc_contract_id") .AsSet(); } and public TTLCServiceMapping() { Table("tab_tlc_services"); Id(x => x.Id, "tlc_service_id"); References(x => x.Contract) .Not.Nullable() .Column("tlc_contract_id"); } and here comes my problem: if I retrieve the list of all contracts in the db, it works. if I retrieve the list of all services in a given contract, I get a StackOverflowException.... Do you see anything wrong with what I wrote? Have I made any mistake? Please let me know if you need any additional information. Oh yes, I missed to say... looking at the stacktrace I see the system is loading all the services and then it is loading again the contracts related to those services. I don't really have the necessary experience nor ideas anymore to understand what's going on.. so any help would be really really great! Thanks in advance, Cheers, Gianluca.

    Read the article

  • NHibernate + ASP.NET + Open Session in View + L2Cache

    - by Pedro
    I am using CodeProject's well known Open Session in View to handle NHibernate Sessions. Does it works well with Level 2 Cache? Anyone has succeeded doing it? Should I use NH.Burrow instead? Any advice on l2 cache in asp.net best practices is appreciated. Edit: link to CodeProject's article: http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx

    Read the article

  • FluentNHibernate - AutoMappings producing incorrect one-to-many column key

    - by Alberto
    Hi I'm new to NHibernate and FNH and am trying to map these simple classes by using FluentNHibernate AutoMappings feature: public class TVShow : Entity { public virtual string Title { get; set;} public virtual ICollection<Season> Seasons { get; protected set; } public TVShow() { Seasons = new HashedSet<Season>(); } public virtual void AddSeason(Season season) { season.TVShow = this; Seasons.Add(season); } public virtual void RemoveSeason(Season season) { if (!Seasons.Contains(season)) { throw new InvalidOperationException("This TV Show does not contain the given season"); } season.TVShow = null; Seasons.Remove(season); } } public class Season : Entity { public virtual TVShow TVShow { get; set; } public virtual int Number { get; set; } public virtual IList<Episode> Episodes { get; set; } public Season() { Episodes = new List<Episode>(); } public virtual void AddEpisode(Episode episode) { episode.Season = this; Episodes.Add(episode); } public virtual void RemoveEpisode(Episode episode) { if (!Episodes.Contains(episode)) { throw new InvalidOperationException("Episode not found on this season"); } episode.Season = null; Episodes.Remove(episode); } } I'm also using a couple of conventions: public class MyForeignKeyConvention : IReferenceConvention { #region IConvention<IManyToOneInspector,IManyToOneInstance> Members public void Apply(FluentNHibernate.Conventions.Instances.IManyToOneInstance instance) { instance.Column("fk_" + instance.Property.Name); } #endregion } The problem is that FNH is generating the section below for the Seasons property mapping: <bag name="Seasons"> <key> <column name="TVShow_Id" /> </key> <one-to-many class="TVShowsManager.Domain.Season, TVShowsManager.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </bag> The column name above should be fk_TVShow rather than TVShow_Id. If amend the hbm files produced by FNH then the code works. Does anyone know what it's wrong? Thanks in advance.

    Read the article

  • Id property not populated

    - by fingers
    I have an identity mapping like so: Id(x => x.GuidId).Column("GuidId") .GeneratedBy.GuidComb().UnsavedValue(Guid.Empty); When I retrieve an object from the database, the GuidId property of my object is Guid.Empty, not the actual Guid (the property in the class is of type System.Guid). However, all of the other properties in the object are populated just fine. The database field's data type (SQL Server 2005) is uniqueidentifier, and marked as RowGuid. The application that is connecting to the database is a VB.NET Web Site project (not a "Web Application" or "MVC Web Application" - just a regular "Web Site" project). I open the NHibernate session through a custom HttpModule. Here is the HttpModule: public class NHibernateModule : System.Web.IHttpModule { public static ISessionFactory SessionFactory; public static ISession Session; private static FluentConfiguration Configuration; static NHibernateModule() { if (Configuration == null) { string connectionString = cfg.ConfigurationManager.ConnectionStrings["myDatabase"].ConnectionString; Configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .ExposeConfiguration(c => c.Properties.Add("current_session_context_class", "web")) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadMap>().ExportTo("C:\\Mappings")); } SessionFactory = Configuration.BuildSessionFactory(); } public void Init(HttpApplication context) { context.BeginRequest += delegate { Session = SessionFactory.OpenSession(); CurrentSessionContext.Bind(Session); }; context.EndRequest += delegate { CurrentSessionContext.Unbind(SessionFactory); }; } public void Dispose() { Session.Dispose(); } } The strangest part of all, is that from my unit test project, the GuidId property is returned as I would expect. I even rigged it to go for the exact row in the exact database as the web site was hitting. The only differences I can think of between the two projects are The unit test project is in C# Something with the way the session is managed between the HttpModule and my unit tests The configuration for the unit tests is as follows: Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005.ConnectionString(cs => cs.Is(connectionString))) .Mappings(x => x.FluentMappings.AddFromAssemblyOf<LeadDetailMap>()); I am fresh out of ideas. Any help would be greatly appreciated. Thanks

    Read the article

  • NHibernate join and projection properties

    - by devgroup
    Hello, I have simple situation (like on the image link text) and simple SQL query SELECT M.Name, A.Name, B.Name FROM Master M LEFT JOIN DetailA A ON M.DescA = A.Id LEFT JOIN DetailB B ON M.DescB = B.Id How to achive the same effect in nHibernate using CriteriaAPI ?

    Read the article

  • NHibernate Pitfalls: Custom Types and Detecting Changes

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports the declaration of properties of user-defined types, that is, not entities, collections or primitive types. These are used for mapping a database columns, of any type, into a different type, which may not even be an entity; think, for example, of a custom user type that converts a BLOB column into an Image. User types must implement interface NHibernate.UserTypes.IUserType. This interface specifies an Equals method that is used for comparing two instances of the user type. If this method returns false, the entity is marked as dirty, and, when the session is flushed, will trigger an UPDATE. So, in your custom user type, you must implement this carefully so that it is not mistakenly considered changed. For example, you can cache the original column value inside of it, and compare it with the one in the other instance. Let’s see an example implementation of a custom user type that converts a Byte[] from a BLOB column into an Image: 1: [Serializable] 2: public sealed class ImageUserType : IUserType 3: { 4: private Byte[] data = null; 5: 6: public ImageUserType() 7: { 8: this.ImageFormat = ImageFormat.Png; 9: } 10: 11: public ImageFormat ImageFormat 12: { 13: get; 14: set; 15: } 16: 17: public Boolean IsMutable 18: { 19: get 20: { 21: return (true); 22: } 23: } 24: 25: public Object Assemble(Object cached, Object owner) 26: { 27: return (cached); 28: } 29: 30: public Object DeepCopy(Object value) 31: { 32: return (value); 33: } 34: 35: public Object Disassemble(Object value) 36: { 37: return (value); 38: } 39: 40: public new Boolean Equals(Object x, Object y) 41: { 42: return (Object.Equals(x, y)); 43: } 44: 45: public Int32 GetHashCode(Object x) 46: { 47: return ((x != null) ? x.GetHashCode() : 0); 48: } 49: 50: public override Int32 GetHashCode() 51: { 52: return ((this.data != null) ? this.data.GetHashCode() : 0); 53: } 54: 55: public override Boolean Equals(Object obj) 56: { 57: ImageUserType other = obj as ImageUserType; 58: 59: if (other == null) 60: { 61: return (false); 62: } 63: 64: if (Object.ReferenceEquals(this, other) == true) 65: { 66: return (true); 67: } 68: 69: return (this.data.SequenceEqual(other.data)); 70: } 71: 72: public Object NullSafeGet(IDataReader rs, String[] names, Object owner) 73: { 74: Int32 index = rs.GetOrdinal(names[0]); 75: Byte[] data = rs.GetValue(index) as Byte[]; 76: 77: this.data = data as Byte[]; 78: 79: if (data == null) 80: { 81: return (null); 82: } 83: 84: using (MemoryStream stream = new MemoryStream(this.data ?? new Byte[0])) 85: { 86: return (Image.FromStream(stream)); 87: } 88: } 89: 90: public void NullSafeSet(IDbCommand cmd, Object value, Int32 index) 91: { 92: if (value != null) 93: { 94: Image data = value as Image; 95: 96: using (MemoryStream stream = new MemoryStream()) 97: { 98: data.Save(stream, this.ImageFormat); 99: value = stream.ToArray(); 100: } 101: } 102: 103: (cmd.Parameters[index] as DbParameter).Value = value ?? DBNull.Value; 104: } 105: 106: public Object Replace(Object original, Object target, Object owner) 107: { 108: return (original); 109: } 110: 111: public Type ReturnedType 112: { 113: get 114: { 115: return (typeof(Image)); 116: } 117: } 118: 119: public SqlType[] SqlTypes 120: { 121: get 122: { 123: return (new SqlType[] { new SqlType(DbType.Binary) }); 124: } 125: } 126: } In this case, we need to cache the original Byte[] data because it’s not easy to compare two Image instances, unless, of course, they are the same.

    Read the article

  • Prevent lazy loading in nHibernate

    - by Ciaran
    Hi, I'm storing some blobs in my database, so I have a Document table and a DocumentContent table. Document contains a filename, description etc and has a DocumentContent property. I have a Silverlight client, so I don't want to load up and send the DocumentContent to the client unless I explicity ask for it, but I'm having trouble doing this. I've read the blog post by Davy Brion. I have tried placing lazy=false in my config and removing the virtual access modifier but have had no luck with it as yet. Every time I do a Session.Get(id), the DocumentContent is retrieved via an outer join. I only want this property to be populated when I explicity join onto this table and ask for it. Any help is appreciated. My NHibernate mapping is as follows: <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Jrm.Model" namespace="Jrm.Model"> <class name="JrmDocument" lazy="false"> <id name="JrmDocumentID"> <generator class="native" /> </id> <property name="FileName"/> <property name="Description"/> <many-to-one name="DocumentContent" class="JrmDocumentContent" unique="true" column="JrmDocumentContentID" lazy="false"/> </class> <class name="JrmDocumentContent" lazy="false"> <id name="JrmDocumentContentID"> <generator class="native" /> </id> <property name="Content" type="BinaryBlob" lazy="false"> <column name="FileBytes" sql-type="varbinary(max)"/> </property> </class> </hibernate-mapping> and my classes are: [DataContract] public class JrmDocument : ModelBase { private int jrmDocumentID; private JrmDocumentContent documentContent; private long maxFileSize; private string fileName; private string description; public JrmDocument() { } public JrmDocument(string fileName, long maxFileSize) { DocumentContent = new JrmDocumentContent(File.ReadAllBytes(fileName)); FileName = new FileInfo(fileName).Name; } [DataMember] public virtual int JrmDocumentID { get { return jrmDocumentID; } set { jrmDocumentID = value; OnPropertyChanged("JrmDocumentID"); } } [DataMember] public JrmDocumentContent DocumentContent { get { return documentContent; } set { documentContent = value; OnPropertyChanged("DocumentContent"); } } [DataMember] public virtual long MaxFileSize { get { return maxFileSize; } set { maxFileSize = value; OnPropertyChanged("MaxFileSize"); } } [DataMember] public virtual string FileName { get { return fileName; } set { fileName = value; OnPropertyChanged("FileName"); } } [DataMember] public virtual string Description { get { return description; } set { description = value; OnPropertyChanged("Description"); } } } [DataContract] public class JrmDocumentContent : ModelBase { private int jrmDocumentContentID; private byte[] content; public JrmDocumentContent() { } public JrmDocumentContent(byte[] bytes) { Content = bytes; } [DataMember] public int JrmDocumentContentID { get { return jrmDocumentContentID; } set { jrmDocumentContentID = value; OnPropertyChanged("JrmDocumentContentID"); } } [DataMember] public byte[] Content { get { return content; } set { content = value; OnPropertyChanged("Content"); } } }

    Read the article

  • NHibernate HiLo - new column per entity and HiLo catches

    - by Gareth
    Im currently using the hilo id generator for my classes but have just been using the minimal of settings eg <class name="ClassA" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" / </id ... But should I really be specifying a new column for NHibernate to use foreach entity and providing it with a max lo? <class name="ClassA" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" <param name="table"hibernate_unique_key</param <param name="column"classA_nexthi</param <param name="max_lo"20</param </generator </id ... <class name="ClassB" <id name="Id" column="id" unsaved-value="0" <generator class="hilo" <param name="table"hibernate_unique_key</param <param name="column"classB_nexthi</param <param name="max_lo"20</param </generator </id ... Also I've noticed that when I do the above the SchemaExport will not create all the columns - only classB_nexthi, is there something else im doing wrong. Thanks

    Read the article

  • Using NHibernate with an EAV data model

    - by devonlazarus
    I'm trying to leverage NH to map to a data model that is a loose interpretation of the EAV/CR data model. I have most of it working but am struggling with mapping the Entity.Attributes collection. Here are the tables in question: -------------------- | Entities | -------------------- | EntityId PK |-| | EntityType | | -------------------- | ------------- | V -------------------- | EntityAttributes | ------------------ --------------------------- -------------------- | Attributes | | StringAttributes | | EntityId PK,FK | ------------------ --------------------------- | AttributeId FK | -> | AttributeId PK | -> | StringAttributeId PK,FK | | AttributeValue | | AttributeType | | AttributeName | -------------------- ------------------ --------------------------- The AttributeValue column is implemented as an sql_variant column and I've implemented an NHibernate.UserTypes.IUserType for it. I can create an EntityAttribute entity and persist it directly so that part of the hierarchy is working. I'm just not sure how to map the EntityAttributes collection to the Entity entity. Note the EntityAttributes table could (and does) contain multiple rows for a given EntityId/AttributeId combination: EntityId AttributeId AttributeValue -------- ----------- -------------- 1 1 Blue 1 1 Green StringAttributes row looks like this for this example: StringAttributeId AttributeName ----------------- -------------- 1 FavoriteColor How can I effectively map this data model to my Entity domain such that Entity.Attributes("FavoriteColors") returns a collection of favorite colors? Typed as System.String?

    Read the article

  • Ordered many-to-many relationship in NHibernate

    - by Kristoffer
    Let's say I have two classes: Item and ItemCollection, where ItemCollection contains an ordered list of Item objects with an index, i.e. the list is ordered in a way specified by the user. Let's also say that they have a many-to-many relationship, an ItemCollection can contain many items and an Item can belong to several ItemCollections. That would, in my head, require three tables in the database. One for Item, one for ItemCollection and one for the ordered mapping. The mapping table would contain three columns: int ItemID int ItemCollectionID int ListIndex QUESTION: How would you design the ItemCollection class? Should the list of Item objects be a list, dictionary or other? What would the NHibernate mapping look like to get the ListIndex into the picture?

    Read the article

  • NHibernate Unique Constraint on Name and Parent Object fails because NH inserts Null

    - by James
    Hi, I have an object as follows Public Class Bin Public Property Id As Integer Public Property Name As String Public Property Store As Store End Class Public Class Store Public Property Id As Integer Public Property Bins As IEnumerable(Of Bin) End Class I have a unique constraint in the database on Bin.Name and BinStoreID to ensure unique names within stores. However, when NHibernate persists the store, it first inserts the Bin records with a null StoreID before performing an update later to set the correct StoreID. This violates the Unique Key If I persist two stores with a Bin of the same name because The Name columns are the same and the StoreID is null for both. Is there something I can add to the mapping to ensure that the correct StoreID is included in the INSERT rather than performing an update later? We are using HiLo identity generation so we are not relying on DB generated identity columns Thanks James

    Read the article

  • NHibernate WCF Bidirectional and Lazy loading

    - by ChrisKolenko
    Hi everyone, I'm just looking for some direction when it comes to NHibernate and WCF. At the moment i have a many to one association between a person and address. The first problem. I have to eager load the list of addresses so it doesn't generate a lazy loaded proxy. Is there a way to disable lazy loading completely? I never want to see it generated. The second problem. The bidirectional association between my poco's is killing my standard serialization. What's the best way forward. Should I remove the Thanks for all your help

    Read the article

  • Same table NHibernate mapping

    - by mircea .
    How can i go about defining a same table relation mapping (mappingbycode) using Nhibernate for instance let's say I have a class: public class Structure{ public int structureId; public string structureName; public Structure rootStructure; } that references the same class as rootStructure. mapper.Class<Structure>(m => { m.Lazy(true); m.Id(u => u.structureId, map => { map.Generator(Generators.Identity); }); m.Property(c => c.structureName); m.? // Same table mapping } ; Thanks

    Read the article

  • Nhibernate ValueType Collection as delimited string in DB

    - by JWendel
    Hi I have a legacy db that I am mapping with Nhibernate. And in several locations a list och strigs or domain objects are mapped as a delimited string in the database. Either 'string|string|string' in the value type cases and like 'domainID|domainID|domainID' in the references type cases. I know I can create a dummy property on the class and map to that fields but I would like to do it in a more clean way, like when mapping Enums as their string representation with the EnumStringType class. Is a IUserType the way to go here? Thanks in advance /Johan

    Read the article

  • Linq to NHibernate - How to return a parent object with only certain child objects included

    - by vakman
    Given a simplified model like the following: public class Enquiry { public virtual DateTime Created { get; set; } public virtual Sender Sender { get; set; } } public class Sender { public virtual IList<Enquiry> Enquiries { get; set; } } How can you construct a Linq to Nhibernate query such that it gives you back a list of senders and their enquiries where the enquiries meet some criteria. I have tried something like this: return session.Linq<Enquiry>() .Where(enquiry => enquiry.Created < DateTime.Now) .Select(enquiry => enquiry.Sender) In this case I get an InvalidCastException saying you can't cast type Sender to type Enquiry. Any pointers on how I can do this without using HQL?

    Read the article

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