Search Results

Search found 12291 results on 492 pages for 'fluent api'.

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

  • Fluent NHibernate - Delete a related object when no explicit relationship exists in the model

    - by John Price
    I've got an application that keeps track of (for the sake of an example) what drinks are available at a given restaurant. My domain model looks like: class Restaurant { public IEnumerable<RestaurantDrink> GetRestaurantDrinks() { ... } //other various properties } class RestaurantDrink { public Restaurant Restaurant { get; set; } public Drink { get; set; } public string DrinkVariety { get; set; } //"fountain drink", "bottled", etc. //other various properties } class Drink { public string Name { get; set; } public string Manufacturer { get; set; } //other various properties } My db schema is (I hope) about what you'd expect; "RestaurantDrinks" is essentially a mapping table between Restaurants and Drinks with some extra properties (like "DrinkVariety" tacked on). Using Fluent NHibernate to set up mappings, I've set up a "HasMany" relationship from Restaurants to RestaurantDrinks that causes the latter to be deleted when its parent Restaurant is deleted. My question is, given that "Drink" does not have any property on it that explicitly references RestaurantDrinks (the relationship only exists in the underlying database), can I set up a mapping that will cause RestaurantDrinks to be deleted if their associated Drink is deleted?

    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

  • Big problem with fluent nhibernate, c# and MySQL need to search in BLOB

    - by VinnyG
    I've done a big mistake, now I have to find a solution. It was my first project working with fluent nhibernate, I mapped an object this way : public PosteCandidateMap() { Id(x => x.Id); Map(x => x.Candidate); Map(x => x.Status); Map(x => x.Poste); Map(x => x.MatchPossibility); Map(x => x.ModificationDate); } So the whole Poste object is in the database but I would have need only the PosteId. Now I got to find all Candidates for one Poste so when I look in my repository I have : return GetAll().Where(x => x.Poste.Id == id).ToList(); But this is very slow since it loads all the items, we now have more than 1500 items in the table, at first to project was not supposed to be that big (not a big paycheck either). Now I'm trying to do this with criterion ou Linq but it's not working since my Poste is in a BLOB. Is there anyway I can change this easyly? Thanks a lot for the help!

    Read the article

  • How to Map Two Tables To One Class in Fluent NHibernate

    - by Richard Nagle
    I am having a problem with fluent nhiberbate mapping two tables to one class. I have the following database schema: TABLE dbo.LocationName ( LocationId INT PRIMARY KEY, LanguageId INT PRIMARY KEY, Name VARCHAR(200) ) TABLE dbo.Language ( LanguageId INT PRIMARY KEY, Locale CHAR(5) ) And want to build the following class definition: public class LocationName { public virtual int LocationId { get; private set; } public virtual int LanguageId { get; private set; } public virtual string Name { get; set; } public virtual string Locale { get; set; } } Here is my mapping class: public LocalisedNameMap() { WithTable("LocationName"); UseCompositeId() .WithKeyProperty(x => x.LanguageId) .WithKeyProperty(x => x.LocationId); Map(x => x.Name); WithTable("Language", lang => { lang.WithKeyColumn("LanguageId"); lang.Map(x => x.Locale); }); } The problem is with the mapping of the Locale field being from another table, and in particular that the keys between those tables don't match. Whenever I run the application with this mapping I get the following error on startup: Foreign key (FK7FC009CCEEA10EEE:Language [LanguageId])) must have same number of columns as the referenced primary key (LocationName [LanguageId, LocationId]) How do I tell nHibernate to map from LocationName to Language using only the LanguageId field?

    Read the article

  • Fluent NHibernate Mappings ClassMap<Entities>....

    - by Pandiya Chendur
    I was going through fluent hibernate getting started tutorial.... In my asp.net mvc web application i have created Entities and Mapping folder as they stated... I created an entity class and i tried to map it my mapping class using this, using System; using System.Collections.Generic; using System.Linq; using System.Web; using FluentNhibernateMVC.Entities; namespace FluentNhibernateMVC.Mappings { public class ClientMap : ClassMap<Client> { } } I cant able to find a ClassMap keyword in my autosuggest list why? This is my entity class using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FluentNhibernateMVC.Entities { public class Client { public int ClientId { get; set; } public string ClientName { get; set; } public string ClientMobNo { get; set; } public string ClientAddress { get; set; } public DateTime CreatedDate { get; set; } public byte IsDeleted { get; set; } public int CreatedBy { get; set; } } } I have added all references to my project...Am i missing some thing...

    Read the article

  • How to create a reference tables for collection classes using fluent nhibernate

    - by Akk
    How can i create a 3 table schema from the following model classes. public class Product { public int Id {get; set;} public string Name {get; set;} public IList<Photo> Photos {get; set;} } public class Photo { public int Id {get; set;} public string Path {get; set;} } I want to create the following table structure in the database: Product ------- Id Name ProductPhotos ------------- ProductId (FK Products.Id) PhotoId (FK Photos.Id) Photos ------ Id Path How i can express the above Database Schema using Fluent NHibernate? I could only manage the following the Mapping but this does not get me the 3rd Photo ref table. public class ProductMap : ClassMap<Product> { public CityMap() { Id(x => x.Id); Map(x => x.Name); Table("Products"); HasMany(x => x.Photos).Table("ProductPhotos").KeyColumn("ProductId"); } }

    Read the article

  • How to create reference tables using fluent nhibernate

    - by Akk
    How can i create a 3 table schema from the following model classes. public class Product { public int Id {get; set;} public string Name {get; set;} public IList<Photo> Photos {get; set;} } public class Photo { public int Id {get; set;} public string Path {get; set;} } I want to create the following table structure in the database: Product ------- Id Name ProductPhotos ------------- ProductId (FK Products.Id) PhotoId (FK Photos.Id) Photos ------ Id Path How i can express the above Database Schema using Fluent NHibernate? I could only manage the following the Mapping but this does not get me the 3rd Photo ref table. public class ProductMap : ClassMap<Product> { public CityMap() { Id(x => x.Id); Map(x => x.Name); Table("Products"); HasMany(x => x.Photos).Table("ProductPhotos").KeyColumn("ProductId"); } }

    Read the article

  • 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

  • Implementing synchronous MediaTypeFormatters in ASP.NET Web API

    - by cibrax
    One of main characteristics of MediaTypeFormatter’s in ASP.NET Web API is that they leverage the Task Parallel Library (TPL) for reading or writing an model into an stream. When you derive your class from the base class MediaTypeFormatter, you have to either implement the WriteToStreamAsync or ReadFromStreamAsync methods for writing or reading a model from a stream respectively. These two methods return a Task, which internally does all the serialization work, as it is illustrated bellow. public abstract class MediaTypeFormatter { public virtual Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext); public virtual Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger); }   .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } However, most of the times, serialization is a safe operation that can be done synchronously. In fact, many of the serializer classes you will find in the .NET framework only provide sync methods. So the question is, how you can transform that synchronous work into a Task ?. Creating a new task using the method Task.Factory.StartNew for doing all the serialization work would be probably the typical answer. That would work, as a new task is going to be scheduled. However, that might involve some unnecessary context switches, which are out of our control and might be affect performance on server code specially.   If you take a look at the source code of the MediaTypeFormatters shipped as part of the framework, you will notice that they actually using another pattern, which uses a TaskCompletionSource class. public Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) {   var tsc = new TaskCompletionSource<AsyncVoid>(); tsc.SetResult(default(AsyncVoid));   //Do all the serialization work here synchronously   return tsc.Task; }   /// <summary> /// Used as the T in a "conversion" of a Task into a Task{T} /// </summary> private struct AsyncVoid { } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } They are basically doing all the serialization work synchronously and using a TaskCompletionSource for returning a task already done. To conclude this post, this is another approach you might want to consider when using serializers that are not compatible with an async model. Update: Henrik Nielsen from the ASP.NET team pointed out the existence of a built-in media type formatter for writing sync formatters. BufferedMediaTypeFormatter http://t.co/FxOfeI5x

    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

  • Pan point on Google Map to specific pixel position on screen (API v3)

    - by Jake
    When overlay is a Google maps overlay and offsetx, offsety is the pixel distance from the maps center that I want to pan latlong to, the following works. var projection = overlay.getProjection(); var pxlocation = projection.fromLatLngToContainerPixel(latlong); map.panTo(projection.fromContainerPixelToLatLng(new google.maps.Point(pxlocation.x+offsetx,pxlocation.y+offsety))); However, I don't always have an overlay on the map and map.getProjection() returns a projection, not a MapCanvasProjection which does not have the methods I need. Is there a way to do this without making an overlay specificaly for it?

    Read the article

  • gdata api + javascript library for accessing documents?

    - by user246114
    Hi, I wanted to do the following with the gdata javascript library: get a list of a user's documents. read the contents of a chosen document. edit its contents, update the document. If I'm reading correctly, this is not supported by the javascript library? I got this to work with the java library, but would like to push this functionality to the client. Is it possible? If not, are there any ways around it? Thank you

    Read the article

  • Using Gdata Calendar API for PHP App to create a calender system with event ownership

    - by linuxlover101
    Hello, I'm working on a PHP app, and I'm trying to find the best way to set up a calendar system. First let me describe the intended function of the system: The application has multiple users who can login simultaneously. Each user should be able to add their own events and display them on their "profile." Also, on another page, the events should be able to be shown all together (from all users) and from each individual users exclusively. Since Google Calendar has a nice calendar-looking interface, I thought I would work with the GData APIs. Originally, I thought this would make things easier. But then it seems that if I want to represent event ownership, either each user would have to have a google account or somehow they all would each have to have a separate calendar. Thus, the application would have to create the calendar (if it does not exist) and be able to edit only their calendar. Two questions: Can I somehow use the GData APIs to accomplish my goal? (Mainly event ownership.) Should I just create my own calendar like application? Thanks!

    Read the article

  • youtube python api gdata.service. requesterror

    - by nashr rafeeg
    i have the following code which is trying to add a set of videos into a youtube play list import urllib,re import gdata.youtube import gdata.youtube.service class reddit(): def __init__(self, rssurl ='http://www.reddit.com/r/chillmusic.rss' ): self.URL = rssurl self._downloadrss() def _downloadrss(self): if self.URL.endswith('.rss'): # Downloadd the RSS feed of the subreddit - save as "feed.rss" try: print "Downloading rss from reddit..." urllib.urlretrieve (URL, "feed.rss") except Exception as e: print e def clean(self): playList = open("feed.rss").read() links = re.findall(r'(http?://www.youtube.com\S+)', playList) for link in links: firstPass = link.replace('&quot;&gt;[link]&lt;/a&gt;', '') secondPass = firstPass.replace('&amp;amp;fmt=18', '') thirdpass = secondPass.replace('&amp;amp;feature=related', '') finalPass = thirdpass.replace('http://www.youtube.com/watch?v=', '') print thirdpass, "\t Extracted: ", finalPass return finalPass class google(): def __init__(self, username, password): self.Username = username self.password = password #do not change any of the following self.key = 'AI39si5DDjGYhG_1W-8n_amjgEjbOU27sa0aw2RQI5gOaoK5KqCD2Fzffbkh8oqGu7CqFQLLQ7N7wK0gz7lrTQbd70srC72Niw' self.appname = 'Reddit playlist maker' self.service = gdata.youtube.service.YouTubeService() def authenticate(self): self.service.email = self.Username self.service.password = self.password self.service.developer_key = self.key self.service.client_id = self.appname self.service.source = self.appname self.service.ssl = False self.service.ProgrammaticLogin() def get_playlists(self): y_playlist = self.service.GetYouTubePlaylistFeed(username='default') l = [] k = [] for p in y_playlist.entry: k=[] k=[p.link[1].href, p.title.text] l.append(k) return l def get_playlist_id_from_url(self, href): #quick and dirty method to get the playList id's return href.replace('http://www.youtube.com/view_play_list?p=','') def creat_playlist(self, name="Reddit list", disc ="videos from reddit"): playlistentry = self.service.AddPlaylist(name, disc) if isinstance(playlistentry, gdata.youtube.YouTubePlaylistEntry): print 'New playlist added' return playlistentry.link[1].href def add_video_to_playlist(self,playlist_uri,video): video_entry = self.service.AddPlaylistVideoEntryToPlaylist( playlist_uri, video) if isinstance(video_entry, gdata.youtube.YouTubePlaylistVideoEntry): print 'Video added' URL = "http://www.reddit.com/r/chillmusic.rss" r = reddit(URL) g = google('[email protected]', 'xxxx') g.authenticate() def search_playlist(playlist="Reddit list3"): pl_id = None for pl in g.get_playlists(): if pl[1] == playlist: pl_id = pl[0] print pl_id break if pl_id == None: pl_id = g.creat_playlist(name=playlist) return pl_id pls = search_playlist() for video_id in r.clean(): g.add_video_to_playlist(pls, video_id) when i run the code i am geting the following error message gdata.service.RequestError: {'status': 303, 'body': '', 'reason': 'See Other'} any one have any idea why i am getting this error cheers Nash

    Read the article

  • google maps api v2 - tens of thousands of markers

    - by Adam
    Hello, my problem is with XXk (aka XX000) markers, atm I have 7k markers and will be more, and more, problem is in marker database, because atm this is 4MB (link to my DB http://tinyurl.com/ybau9ce) and problem is, how load that fast? for example DOWNLOAD only this what are show now, DOWNLOAD because load I have with ClusterMarker and problem is not with java but with download that database I think...

    Read the article

  • gdata youtube api 302 'The document has moved'

    - by zalew
    I'm trying to get YouTube feeds with the python gdata library. Authentication features work ok, yt_service.ProgrammaticLogin() works, generating subauth token works, etc., but when I try to get some feeds (GetMostRecentVideoFeed, GetYouTubeVideoEntry, even GetFeed, and any other) I get: RequestError: {'status': 302, 'body': '<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">\n<TITLE>302 Moved</TITLE></HEAD><BODY>\n<H1>302 Moved</H1>\nThe document has moved\n<A HREF="http://www.google.com">here</A>.\r\n</BODY></HTML>\r\n', 'reason': 'Redirect received, but redirects_remaining <= 0'} 302 to 'google.com'??? I've even tried to do something from the google online tutorials and I get the same error. What's going on?

    Read the article

  • Google Maps iPhone API Terrain View

    - by Adam
    We're using MapKit on an iPhone app to display a Google Map with terrain view. However, the terrain view only shows when the user has an active Internet connection, the moment the user's Internet is off, the terrain on the map disappears and it appears flat. Is there any way to keep the terrain view on even when the user isn't on an active internet connection? Thanks! Adam

    Read the article

  • Google Place API marker issue

    - by user2959740
    I am creating itinerary planner like http://www.plnnr.com I want to create Google Place marker by direction(North,East,west,south) for e.g. When people select 4 day it should show attraction for 1st day all north location 2nd day east location then south and west. How to i do the auto marker. I am not sure how plnnr.com works how they are generating the lines based on direction. Please anyone help me on this.

    Read the article

  • Google Maps API v3 - Directions/Paths breaking KML Overlay Infowindows

    - by Douglas
    I'm in the end stages before content filling and then production on the Google Maps project I've been working on. A number of bugs and such have been thwarted, but this latest one has me relatively stumped. The demo map can be viewed here: http://dougglover.com/samples/finalProduct/ Everything works fine until you create a path using the Directions section(not to be confused with Get Directions). To reproduce the problem, play around with the map, click on a building or two, just to see the functionality. After ensuring that clicking on a building works(brings up an infowindow), choose two buildings to get directions to in the Directions area. It works great with the routing algorithm I've implemented, and the paths show up nicely, and intelligently. The problem being that you can't click buildings anymore to see their info. I'm assuming it has something to do with the z-index error popping up in the console, but I'm not sure how to handle that if it is the problem. Any guidance is greatly appreciated. :)

    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

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