Search Results

Search found 3444 results on 138 pages for 'mapping'.

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

  • Fill object data from several tables using hibernate mapping

    - by Udo Fholl
    Hi all, I'd like to know if it is possible to fill up a class data from database using the hibernate hbm (mapping). For instance: public class someClass { List<OtherClass> otherClasses; List<YetAnotherClass> yetAnotherClasses; //Constructors ? class OtherClass { String name; //setters, getters } class YetAnotherClass { String name; //setters, getters } //setters, getters } Using an hbm can I fill in the data from tables OTHER_CLASS_TABLE and YET_ANOTHER_CLASS_TABLE? I have no such SOME_CLASS_TABLE since this info is for viewing only. I've been playing with the <join table=""><subselect> and different constructors... But it is not working Thanks! Sorry for my english!

    Read the article

  • nhibernate : mapping to column other than primary key

    - by frosty
    I have the following map. My intention is for the order.BasketId to map to orderItem.BasketId. Tho when i look at the sql i see that it's mapping order.Id to orderItem.BasketId. How do i define in my order map which order property to map against basketId. It seems to default to the primary key. <property name="BasketId" column="Basket_ID" type="Int32"/> <set name="OrderItems" table="item_basket_contents" generic="true" inverse="true" > <key column="Basket_ID" /> <one-to-many class="EStore.Domain.Model.OrderItem, EStore.Domain"/> </set>

    Read the article

  • Mapping enum to a table with hibernate annotation

    - by Thierry-Dimitri Roy
    I have a table DEAL and a table DEAL_TYPE. I would like to map this code: public class Deal { DealType type; } public enum DealType { BASE("Base"), EXTRA("Extra"); } The problem is that the data already exist in the database. And I'm having a hard time mapping the classes to the database. The database looks something like that: TABLE DEAL { Long id; Long typeId; } TABLE DEAL_TYPE { Long id; String text; } I know I could use a simple @OneToMany relationship from deal to deal type, but I would prefer to use an enum. Is this possible? I almost got it working by using a EnumType.ORDINAL type. But unfortunately, my IDs in my deal type table are not sequential, and do not start at 1. Any suggestions?

    Read the article

  • JPA hibernate OneToOne mapping

    - by Stupidfrog
    enviroment: hibernate 4.1.6.final spring 3.1.2.release spring jpa 1.1.0.release postgresql 9.1-901-1.jdbc4 there is 2 table public A { private Long id; private Long name; } public B { private Long id; private Long table_a_id; } the A.id and B.id is sequential, unique , but no related.(means they are separately id for their own table). how to do mapping? i have tried some method, however the result is not i wanted, because it bind wrong. for example: public A { .... @OneToOne @JoinColumn(name = "id") private B table_b } public B { ... @JsonIgnore @OneToOne(mappedBy = "table_b") private A table_a; } when i query A the result is { "id":5, "table_b":{ "id":5, "table_a_id":4 } } obviously the data join by using their id but not joining using table_a_id. what i expect is { "id":4, "table_b":{ "id":5, "table_a_id":4 } } so can somebody teach me that, how to map this 2 table by using table b table_a_id(foregin key)

    Read the article

  • Mapping to a different view based on child type

    - by Ryan Burnham
    So i have a situation where i have common base type but i need to map to a different view based on the child type. It looks like i can use a generic mapping class to handle the inheritance http://geekswithblogs.net/nharrison/archive/2010/07/09/inheriting-a-class-map-in-fluent-nhibernate.aspx But how can i conditionally map to a different view based on the child type? I see an EntityType property but it says its obsolete and will be made private in the next version. As an example i have a base class of ContactInfo is standard between contact types but the values come from different places depending on the contact type, this I'll handle through the sql view.

    Read the article

  • Efficient mapping for a particular finite integer set

    - by R..
    I'm looking for a small, fast (in both directions) bijective mapping between the following list of integers and a subset of the range 0-127: 0x200C, 0x200D, 0x200E, 0x200F, 0x2013, 0x2014, 0x2015, 0x2017, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D, 0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A, 0x20AA, 0x20AB, 0x20AC, 0x20AF, 0x2116, 0x2122 One obvious solution is: y = x>>2 & 0x40 | x & 0x3f; x = 0x2000 | y<<2 & 0x100 | y & 0x3f; Edit: I was missing some of the values, particularly 0x20Ax, which don't work with the above. Another obvious solution is a lookup table, but without making it unnecessarily large, a lookup table would require some bit rearrangement anyway and I suspect the whole task can be better accomplished with simple bit rearrangement. For the curious, those magic numbers are the only "large" Unicode codepoints that appear in legacy ISO-8859 and Windows codepages.

    Read the article

  • Mapping interface or abstract class component

    - by Yann Trevin
    Please consider the following simple use case: public class Foo { public virtual int Id { get; protected set; } public virtual IBar Bar { get; set; } } public interface IBar { string Text { get; set; } } public class Bar : IBar { public virtual string Text { get; set; } } And the fluent-nhibernate map class: public class FooMap : ClassMap<Foo> { public FooMap() { Id(x => x.Id); Component(x => x.Bar, m => { m.Map(x => x.Text); }); } } While running any query with configuration, I get the following exception: NHibernate.InstantiationException: "Cannot instantiate abstract class or interface: NHMappingTest.IBar" It seems that NHibernate tries to instantiate an IBar object instead of the Bar concrete class. How to let Fluent-NHibernate know which concrete class to instantiate when the property returns an interface or an abstract base class? EDIT: Explicitly specify the type of component by writing Component<Bar> (as suggested by Sly) has no effect and causes the same exception to occur. EDIT2: Thanks to vedklyv and Paul Batum: such a mapping should be soon is now possible.

    Read the article

  • fluent nHibernate mapping of subclassed structure

    - by Codezy
    I have a workflow class that has a collection of phases, each phase has a collection of tasks. You can design a workflow that will be used by many engagements. When used in engagement I want to be able to add properties to each class (workflow, phase, and task). For example a task in the designer does not have people assigned, but a task in an engagement would need extra properties like who is assigned to it. I have tried many different approaches using subclasses or interfaces but I just can't get it to map the way I want. Currently I have the engagement level versions as subclasses, but I can't get Engagement phases to map to engagement workflows. Public Class WorkflowMapping Inherits ClassMap(Of Workflow) Sub New() Id(Function(x As Workflow) x.Id).Column("Workflow_Id").GeneratedBy.Identity() Map(Function(x As Workflow) x.Description) Map(Function(x As Workflow) x.Generation) Map(Function(x As Workflow) x.IsActive) HasMany(Function(x As Workflow) x.Phases).Cascade.All() End Sub End Class Public Class EngagementWorkflowMapping Inherits SubclassMap(Of EngagementWorkflow) Sub New() Map(Function(x As EngagementWorkflow) x.ClientNo) Map(Function(x As EngagementWorkflow) x.EngagementNo) End Sub End Class How would you approach mapping this in fluent (or hbm) so that you could load just the workflow base class when designing the flow, or the engagement subclass versions of each when being used by an engagement?

    Read the article

  • nHibernate Self Join Mapping

    - by kmoo01
    Hi Guys, This is probably incredibly simple, but I just cant see the wood for the trees at the moment. For brevity, I would like to model a word object, that has related words to it (synonyms), In doing so I could have the following mappings: <class name="Word" table="bs_word"> <id name="Id" column="WordId" type="Int32" unsaved-value="-1"> <generator class="native"> <param name="sequence"></param> </generator> </id> <property name="Key" column="word" type="String" length="50" /> <many-to-one name="SynonymGroup" class="BS.Core.Domain.Synonym, BS.Core" column="SynonymId" lazy="false"/> <class name="Synonym" table="bs_Synonym"> <id name="Id" column="SynonymId" type="Int32" unsaved-value="-1"> <generator class="native"> <param name="sequence"></param> </generator> </id> <property name="Alias" column="Alias" type="String" length="50" /> <bag name="Words" cascade="none" lazy="false" inverse="true"> <key column="SynonymId" /> <one-to-many class="Word" /> </bag> Mapping it like this would mean for a given word, I can access related words (synonyms) like this: word.SynonymGroup.Words However I would like to know if it is possible to map a bag of objects on an instance of a word object...if that makes sense, so I can access the related words like this: word.Words I've tried playing around with the map element, and composite elements, all to no avail - so I was wondering if some kind person could point me in the right direction? ta, kmoo01

    Read the article

  • Hibernate one-to-one mapping

    - by Andrey Yaskulsky
    I have one-to-one hibernate mapping between class Student and class Points: @Entity @Table(name = "Users") public class Student implements IUser { @Id @Column(name = "id") private int id; @Column(name = "name") private String name; @Column(name = "password") private String password; @OneToOne(fetch = FetchType.EAGER, mappedBy = "student") private Points points; @Column(name = "type") private int type = getType(); //gets and sets... @Entity @Table(name = "Points") public class Points { @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "student")) @Id @GeneratedValue(generator = "generator") @Column(name = "id", unique = true, nullable = false) private int Id; @OneToOne @PrimaryKeyJoinColumn private Student student; //gets and sets And then i do: Student student = new Student(); student.setId(1); student.setName("Andrew"); student.setPassword("Password"); Points points = new Points(); points.setPoints(0.99); student.setPoints(points); points.setStudent(student); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(student); session.getTransaction().commit(); And hibernate saves student in the table but not saves corresponding points. Is it OK? Should i save points separately?

    Read the article

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

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

    Read the article

  • Problem cube mapping in OpenGL using DDS compressed images

    - by Paul Jones
    Hi All, I am having trouble cube mapping when using a DDS cube map, I'm just getting a black cube which leads me to believe I have missing something simple, here's the code so far: DDS_IMAGE_DATA *pDDSImageData = LoadDDSFile(filename); //compressedTexture = -1; if(pDDSImageData != NULL) { int height = pDDSImageData->height; int width = pDDSImageData->width; int numMipMaps = pDDSImageData->numMipMaps; int blockSize; GLenum cubefaces[6] = { GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; if( pDDSImageData->format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT ) blockSize = 8; else blockSize = 16; glGenTextures( 1, &textureId ); int nSize; int nOffset = 0; glEnable(GL_TEXTURE_CUBE_MAP); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); for(int face = 0; face < 6; face++) { for( int i = 0; i < numMipMaps; i++ ) { if( width == 0 ) width = 1; if( height == 0 ) height = 1; glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); nSize = ((width+3)>>2) * ((height+3)>>2) * blockSize; glCompressedTexImage2D(cubefaces[face] , i, pDDSImageData->format, width, height, 0, nSize, pDDSImageData->pixels + nOffset ); nOffset += nSize; // Half the image size for the next mip-map level... width = (width / 2); height = (height / 2); } } } Once this code is called I bind the texture using glBindTexture and draw a cube using GL_QUADS and glTexCoord3f. Thank you for reading and all comments are welcome, sorry if any of the formatting comes out wrong.

    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

  • Will the following NHibernate interface mapping work?

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

    Read the article

  • Mapping an instance of IList in NHibernate

    - by Martin Kirsche
    I'm trying to map a parent-child relationship using NHibernate (2.1.2), MySql.Data (6.2.2) and MySQL Server (5.1). I figured out that this must be done using a <bag> in the mapping file. I build a test app which is running without yielding any errors and is doing an insert for each entry but somehow the foreign key inside the children table (ParentId) is always empty (null). Here are the important parts of my code... Parent public class Parent { public virtual int Id { get; set; } public virtual IList<Child> Children { get; set; } } <class name="Parent"> <id name="Id"> <generator class="native"/> </id> <bag name="Children" cascade="all"> <key column="ParentId"/> <one-to-many class="Child"/> </bag> </class> Child public class Child { public virtual int Id { get; set; } } <class name="Child"> <id name="Id"> <generator class="native"/> </id> </class> Program using (ISession session = sessionFactory.OpenSession()) { session.Save( new Parent() { Children = new List<Child>() { new Child(), new Child() } }); } Any ideas what I did wrong?

    Read the article

  • NHibernate mapping with two special cases

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

    Read the article

  • nhibernate mapping: delete collection, insert new collection with old IDs

    - by npeBeg
    my issue lokks similar to this one: (link) but i have one-to-many association: <set name="Fields" cascade="all-delete-orphan" lazy="false" inverse="true"> <key column="[TEMPLATE_ID]"></key> <one-to-many class="MyNamespace.Field, MyLibrary"/> </set> (i also tried to use ) this mapping is for Template object. this one and the Field object has their ID generators set to identity. so when i call session.Update for the Template object it works fine, well, almost: if the Field object has an Id number, UPDATE sql request is called, if the Id is 0, the INSERT is performed. But if i delete a Field object from the collection it has no effect for the Database. I found that if i also call session.Delete for this Field object, everything will be ok, but due to client-server architecture i don't know what to delete. so i decided to delete all the collection elements from the DB and call session.Update with a new collection. and i've got an issue: nhibernate performs the UPDATE operation for the Field objects that has non-zero Id, but they are removed from DB! maybe i should use some other Id generator or smth.. what is the best way to make nhibernate perform "delete all"/"insert all" routine for the collection?

    Read the article

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

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

    Read the article

  • Nhibernate: mapping two different properties between the same 2 entities

    - by Carlos Decas
    I have a Class A: public class ClassA { public int ID {get; private set;} public string Code {get; private set;} public ClassB B {get; private set;} public IList<ClassB> ListB {get; private set;} } And a ClassB: public class ClassB { public int ID {get; private set;} public string Code {get; private set;} public ClassA A {get; private set;} //some other attributes... } And the Mappings: public ClassAMap() { Table("ClassA"); Id(classA => classA .ID, "ID").GeneratedBy.Identity(); Map(classA => classA.Code, "Code").Unique().Not.Nullable(); //HERE IS THE PROBLEM: -------- References(classA => classA.B,"IDClassB").Cascade.SaveUpdate(); //----- HasMany(classA => classA.ListB).Table("ClassB").KeyColumn("IDClassA").AsBag().Not.LazyLoad().Inverse().Cascade.AllDeleteOrphan(); } ClassB Mappings: public ClassBMap() { Table("ClassB"); Id(classB => classB.ID).GeneratedBy.Identity(); References(classB => classB.A, "IDClassA").ForeignKey("ID").Cascade.SaveUpdate(); } The mappings for ListB in classA worked ok, because at first the was only ListB property and not B, when i had to map B i tried this: References(classA => classA.B,"IDClassB"); The mapping test failed because B wasn't saved, so i did this: References(classA => classA.B,"IDClassB").Cascade.SaveUpdate(); This time B was saved, but by saving B, classA was inserted two times, by A.B and by B.A. How can i solve this problem? Why does it work for the ListB property and not for the B property? Thanks

    Read the article

  • Mapping UrlEncoded POST Values in ASP.NET Web API

    - by Rick Strahl
    If there's one thing that's a bit unexpected in ASP.NET Web API, it's the limited support for mapping url encoded POST data values to simple parameters of ApiController methods. When I first looked at this I thought I was doing something wrong, because it seems mighty odd that you can bind query string values to parameters by name, but can't bind POST values to parameters in the same way. To demonstrate here's a simple example. If you have a Web API method like this:[HttpGet] public HttpResponseMessage Authenticate(string username, string password) { …} and then hit with a URL like this: http://localhost:88/samples/authenticate?Username=ricks&Password=sekrit it works just fine. The query string values are mapped to the username and password parameters of our API method. But if you now change the method to work with [HttpPost] instead like this:[HttpPost] public HttpResponseMessage Authenticate(string username, string password) { …} and hit it with a POST HTTP Request like this: POST http://localhost:88/samples/authenticate HTTP/1.1 Host: localhost:88 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Content-type: application/x-www-form-urlencoded Content-Length: 30 Username=ricks&Password=sekrit you'll find that while the request works, it doesn't actually receive the two string parameters. The username and password parameters are null and so the method is definitely going to fail. When I mentioned this over Twitter a few days ago I got a lot of responses back of why I'd want to do this in the first place - after all HTML Form submissions are the domain of MVC and not WebAPI which is a valid point. However, the more common use case is using POST Variables with AJAX calls. The following is quite common for passing simple values:$.post(url,{ Username: "Rick", Password: "sekrit" },function(result) {…}); but alas that doesn't work. How ASP.NET Web API handles Content Bodies Web API supports parsing content data in a variety of ways, but it does not deal with multiple posted content values. In effect you can only post a single content value to a Web API Action method. That one parameter can be very complex and you can bind it in a variety of ways, but ultimately you're tied to a single POST content value in your parameter definition. While it's possible to support multiple parameters on a POST/PUT operation, only one parameter can be mapped to the actual content - the rest have to be mapped to route values or the query string. Web API treats the whole request body as one big chunk of data that is sent to a Media Type Formatter that's responsible for de-serializing the content into whatever value the method requires. The restriction comes from async nature of Web API where the request data is read only once inside of the formatter that retrieves and deserializes it. Because it's read once, checking for content (like individual POST variables) first is not possible. However, Web API does provide a couple of ways to access the form POST data: Model Binding - object property mapping to bind POST values FormDataCollection - collection of POST keys/values ModelBinding POST Values - Binding POST data to Object Properties The recommended way to handle POST values in Web API is to use Model Binding, which maps individual urlencoded POST values to properties of a model object provided as the parameter. Model binding requires a single object as input to be bound to the POST data, with each POST key that matches a property name (including nested properties like Address.Street) being mapped and updated including automatic type conversion of simple types. This is a very nice feature - and a familiar one from MVC - that makes it very easy to have model objects mapped directly from inbound data. The obvious drawback with Model Binding is that you need a model for it to work: You have to provide a strongly typed object that can receive the data and this object has to map the inbound data. To rewrite the example above to use ModelBinding I have to create a class maps the properties that I need as parameters:public class LoginData { public string Username { get; set; } public string Password { get; set; } } and then accept the data like this in the API method:[HttpPost] public HttpResponseMessage Authenticate(LoginData login) { string username = login.Username; string password = login.Password; … } This works fine mapping the POST values to the properties of the login object. As a side benefit of this method definition, the method now also allows posting of JSON or XML to the same endpoint. If I change my request to send JSON like this: POST http://localhost:88/samples/authenticate HTTP/1.1 Host: localhost:88 Accept: application/jsonContent-type: application/json Content-Length: 40 {"Username":"ricks","Password":"sekrit"} it works as well and transparently, courtesy of the nice Content Negotiation features of Web API. There's nothing wrong with using Model binding and in fact it's a common practice to use (view) model object for inputs coming back from the client and mapping them into these models. But it can be  kind of a hassle if you have AJAX applications with a ton of backend hits, especially if many methods are very atomic and focused and don't effectively require a model or view. Not always do you have to pass structured data, but sometimes there are just a couple of simple response values that need to be sent back. If all you need is to pass a couple operational parameters, creating a view model object just for parameter purposes seems like overkill. Maybe you can use the query string instead (if that makes sense), but if you can't then you can often end up with a plethora of 'message objects' that serve no further  purpose than to make Model Binding work. Note that you can accept multiple parameters with ModelBinding so the following would still work:[HttpPost] public HttpResponseMessage Authenticate(LoginData login, string loginDomain) but only the object will be bound to POST data. As long as loginDomain comes from the querystring or route data this will work. Collecting POST values with FormDataCollection Another more dynamic approach to handle POST values is to collect POST data into a FormDataCollection. FormDataCollection is a very basic key/value collection (like FormCollection in MVC and Request.Form in ASP.NET in general) and then read the values out individually by querying each. [HttpPost] public HttpResponseMessage Authenticate(FormDataCollection form) { var username = form.Get("Username"); var password = form.Get("Password"); …} The downside to this approach is that it's not strongly typed, you have to handle type conversions on non-string parameters, and it gets a bit more complicated to test such as setup as you have to seed a FormDataCollection with data. On the other hand it's flexible and easy to use and especially with string parameters is easy to deal with. It's also dynamic, so if the client sends you a variety of combinations of values on which you make operating decisions, this is much easier to work with than a strongly typed object that would have to account for all possible values up front. The downside is that the code looks old school and isn't as self-documenting as a parameter list or object parameter would be. Nevertheless it's totally functionality and a viable choice for collecting POST values. What about [FromBody]? Web API also has a [FromBody] attribute that can be assigned to parameters. If you have multiple parameters on a Web API method signature you can use [FromBody] to specify which one will be parsed from the POST content. Unfortunately it's not terribly useful as it only returns content in raw format and requires a totally non-standard format ("=content") to specify your content. For more info in how FromBody works and several related issues to how POST data is mapped, you can check out Mike Stalls post: How WebAPI does Parameter Binding Not really sure where the Web API team thought [FromBody] would really be a good fit other than a down and dirty way to send a full string buffer. Extending Web API to make multiple POST Vars work? Don't think so Clearly there's no native support for multiple POST variables being mapped to parameters, which is a bit of a bummer. I know in my own work on one project my customer actually found this to be a real sticking point in their AJAX backend work, and we ended up not using Web API and using MVC JSON features instead. That's kind of sad because Web API is supposed to be the proper solution for AJAX backends. With all of ASP.NET Web API's extensibility you'd think there would be some way to build this functionality on our own, but after spending a bit of time digging and asking some of the experts from the team and Web API community I didn't hear anything that even suggests that this is possible. From what I could find I'd say it's not possible primarily because Web API's Routing engine does not account for the POST variable mapping. This means [HttpPost] methods with url encoded POST buffers are not mapped to the parameters of the endpoint, and so the routes would never even trigger a request that could be intercepted. Once the routing doesn't work there's not much that can be done. If somebody has an idea how this could be accomplished I would love to hear about it. Do we really need multi-value POST mapping? I think that that POST value mapping is a feature that one would expect of any API tool to have. If you look at common APIs out there like Flicker and Google Maps etc. they all work with POST data. POST data is very prominent much more so than JSON inputs and so supporting as many options that enable would seem to be crucial. All that aside, Web API does provide very nice features with Model Binding that allows you to capture many POST variables easily enough, and logistically this will let you build whatever you need with POST data of all shapes as long as you map objects. But having to have an object for every operation that receives a data input is going to take its toll in heavy AJAX applications, with a lot of types created that do nothing more than act as parameter containers. I also think that POST variable mapping is an expected behavior and Web APIs non-support will likely result in many, many questions like this one: How do I bind a simple POST value in ASP.NET WebAPI RC? with no clear answer to this question. I hope for V.next of WebAPI Microsoft will consider this a feature that's worth adding. Related Articles Passing multiple POST parameters to Web API Controller Methods Mike Stall's post: How Web API does Parameter Binding Where does ASP.NET Web API Fit?© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Mapping between 4+1 architectural view model & UML

    - by Sadeq Dousti
    I'm a bit confused about how the 4+1 architectural view model maps to UML. Wikipedia gives the following mapping: Logical view: Class diagram, Communication diagram, Sequence diagram. Development view: Component diagram, Package diagram Process view: Activity diagram Physical view: Deployment diagram Scenarios: Use-case diagram The paper Role of UML Sequence Diagram Constructs in Object Lifecycle Concept gives the following mapping: Logical view (class diagram (CD), object diagram (OD), sequence diagram (SD), collaboration diagram (COD), state chart diagram (SCD), activity diagram (AD)) Development view (package diagram, component diagram), Process view (use case diagram, CD, OD, SD, COD, SCD, AD), Physical view (deployment diagram), and Use case view (use case diagram, OD, SD, COD, SCD, AD) which combines the four mentioned above. The web page UML 4+1 View Materials presents the following mapping: Finally, the white paper Applying 4+1 View Architecture with UML 2 gives yet another mapping: Logical view class diagrams, object diagrams, state charts, and composite structures Process view sequence diagrams, communication diagrams, activity diagrams, timing diagrams, interaction overview diagrams Development view component diagrams Physical view deployment diagram Use case view use case diagram, activity diagrams I'm sure further search will reveal other mappings as well. While various people usually have different perspectives, I don't see why this is the case here. Specially, each UML diagram describes the system from a particular aspect. So, for instance, why the "sequence diagram" is considered as describing the "logical view" of the system by one author, while another author considers it as describing the "process view"? Could you please help me clarify the confusion?

    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

  • Mixing inheritance mapping strategies in NHibernate

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

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5: Part 2 – Table per Type (TPT)

    - by mortezam
    In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH may be too serious for our design since it results in denormalized schemas that can become a major burden in the long run. In today’s blog post we are going to learn about Table per Type (TPT) as another inheritance mapping strategy and we'll see that TPT doesn’t expose us to this problem. Table per Type (TPT)Table per Type is about representing inheritance relationships as relational foreign key associations. Every class/subclass that declares persistent properties—including abstract classes—has its own table. The table for subclasses contains columns only for each noninherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the base class table. This approach is shown in the following figure: For example, if an instance of the CreditCard subclass is made persistent, the values of properties declared by the BillingDetail base class are persisted to a new row of the BillingDetails table. Only the values of properties declared by the subclass (i.e. CreditCard) are persisted to a new row of the CreditCards table. The two rows are linked together by their shared primary key value. Later, the subclass instance may be retrieved from the database by joining the subclass table with the base class table. TPT Advantages The primary advantage of this strategy is that the SQL schema is normalized. In addition, schema evolution is straightforward (modifying the base class or adding a new subclass is just a matter of modify/add one table). Integrity constraint definition are also straightforward (note how CardType in CreditCards table is now a non-nullable column). Another much more important advantage is the ability to handle polymorphic associations (a polymorphic association is an association to a base class, hence to all classes in the hierarchy with dynamic resolution of the concrete class at runtime). A polymorphic association to a particular subclass may be represented as a foreign key referencing the table of that particular subclass. Implement TPT in EF Code First We can create a TPT mapping simply by placing Table attribute on the subclasses to specify the mapped table name (Table attribute is a new data annotation and has been added to System.ComponentModel.DataAnnotations namespace in CTP5): public abstract class BillingDetail {     public int BillingDetailId { get; set; }     public string Owner { get; set; }     public string Number { get; set; } } [Table("BankAccounts")] public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } [Table("CreditCards")] public class CreditCard : BillingDetail {     public int CardType { get; set; }     public string ExpiryMonth { get; set; }     public string ExpiryYear { get; set; } } public class InheritanceMappingContext : DbContext {     public DbSet<BillingDetail> BillingDetails { get; set; } } If you prefer fluent API, then you can create a TPT mapping by using ToTable() method: protected override void OnModelCreating(ModelBuilder modelBuilder) {     modelBuilder.Entity<BankAccount>().ToTable("BankAccounts");     modelBuilder.Entity<CreditCard>().ToTable("CreditCards"); } Generated SQL For QueriesLet’s take an example of a simple non-polymorphic query that returns a list of all the BankAccounts: var query = from b in context.BillingDetails.OfType<BankAccount>() select b; Executing this query (by invoking ToList() method) results in the following SQL statements being sent to the database (on the bottom, you can also see the result of executing the generated query in SQL Server Management Studio): Now, let’s take an example of a very simple polymorphic query that requests all the BillingDetails which includes both BankAccount and CreditCard types: projects some properties out of the base class BillingDetail, without querying for anything from any of the subclasses: var query = from b in context.BillingDetails             select new { b.BillingDetailId, b.Number, b.Owner }; -- var query = from b in context.BillingDetails select b; This LINQ query seems even more simple than the previous one but the resulting SQL query is not as simple as you might expect: -- As you can see, EF Code First relies on an INNER JOIN to detect the existence (or absence) of rows in the subclass tables CreditCards and BankAccounts so it can determine the concrete subclass for a particular row of the BillingDetails table. Also the SQL CASE statements that you see in the beginning of the query is just to ensure columns that are irrelevant for a particular row have NULL values in the returning flattened table. (e.g. BankName for a row that represents a CreditCard type) TPT ConsiderationsEven though this mapping strategy is deceptively simple, the experience shows that performance can be unacceptable for complex class hierarchies because queries always require a join across many tables. In addition, this mapping strategy is more difficult to implement by hand— even ad-hoc reporting is more complex. This is an important consideration if you plan to use handwritten SQL in your application (For ad hoc reporting, database views provide a way to offset the complexity of the TPT strategy. A view may be used to transform the table-per-type model into the much simpler table-per-hierarchy model.) SummaryIn this post we learned about Table per Type as the second inheritance mapping in our series. So far, the strategies we’ve discussed require extra consideration with regard to the SQL schema (e.g. in TPT, foreign keys are needed). This situation changes with the Table per Concrete Type (TPC) that we will discuss in the next post. References ADO.NET team blog Java Persistence with Hibernate book a { text-decoration: none; } a:visited { color: Blue; } .title { padding-bottom: 5px; font-family: Segoe UI; font-size: 11pt; font-weight: bold; padding-top: 15px; } .code, .typeName { font-family: consolas; } .typeName { color: #2b91af; } .padTop5 { padding-top: 5px; } .padTop10 { padding-top: 10px; } p.MsoNormal { margin-top: 0in; margin-right: 0in; margin-bottom: 10.0pt; margin-left: 0in; line-height: 115%; font-size: 11.0pt; font-family: "Calibri" , "sans-serif"; }

    Read the article

  • Class Mapping Error: 'T' must be a non-abstract type with a public parameterless constructor

    - by Amit Ranjan
    Hi, While mapping class i am getting error 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. Below is my SqlReaderBase Class public abstract class SqlReaderBase<T> : ConnectionProvider { #region Abstract Methods protected abstract string commandText { get; } protected abstract CommandType commandType { get; } protected abstract Collection<IDataParameter> GetParameters(IDbCommand command); **protected abstract MapperBase<T> GetMapper();** #endregion #region Non Abstract Methods /// <summary> /// Method to Execute Select Queries for Retrieveing List of Result /// </summary> /// <returns></returns> public Collection<T> ExecuteReader() { //Collection of Type on which Template is applied Collection<T> collection = new Collection<T>(); // initializing connection using (IDbConnection connection = GetConnection()) { try { // creates command for sql operations IDbCommand command = connection.CreateCommand(); // assign connection to command command.Connection = connection; // assign query command.CommandText = commandText; //state what type of query is used, text, table or Sp command.CommandType = commandType; // retrieves parameter from IDataParameter Collection and assigns it to command object foreach (IDataParameter param in GetParameters(command)) command.Parameters.Add(param); // Establishes connection with database server connection.Open(); // Since it is designed for executing Select statements that will return a list of results // so we will call command's execute reader method that return a Forward Only reader with // list of results inside. using (IDataReader reader = command.ExecuteReader()) { try { // Call to Mapper Class of the template to map the data to its // respective fields MapperBase<T> mapper = GetMapper(); collection = mapper.MapAll(reader); } catch (Exception ex) // catch exception { throw ex; // log errr } finally { reader.Close(); reader.Dispose(); } } } catch (Exception ex) { throw ex; } finally { connection.Close(); connection.Dispose(); } } return collection; } #endregion } What I am trying to do is , I am executine some command and filling my class dynamically. The class is given below: namespace FooZo.Core { public class Restaurant { #region Private Member Variables private int _restaurantId = 0; private string _email = string.Empty; private string _website = string.Empty; private string _name = string.Empty; private string _address = string.Empty; private string _phone = string.Empty; private bool _hasMenu = false; private string _menuImagePath = string.Empty; private int _cuisine = 0; private bool _hasBar = false; private bool _hasHomeDelivery = false; private bool _hasDineIn = false; private int _type = 0; private string _restaurantImagePath = string.Empty; private string _serviceAvailableTill = string.Empty; private string _serviceAvailableFrom = string.Empty; public string Name { get { return _name; } set { _name = value; } } public string Address { get { return _address; } set { _address = value; } } public int RestaurantId { get { return _restaurantId; } set { _restaurantId = value; } } public string Website { get { return _website; } set { _website = value; } } public string Email { get { return _email; } set { _email = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public bool HasMenu { get { return _hasMenu; } set { _hasMenu = value; } } public string MenuImagePath { get { return _menuImagePath; } set { _menuImagePath = value; } } public string RestaurantImagePath { get { return _restaurantImagePath; } set { _restaurantImagePath = value; } } public int Type { get { return _type; } set { _type = value; } } public int Cuisine { get { return _cuisine; } set { _cuisine = value; } } public bool HasBar { get { return _hasBar; } set { _hasBar = value; } } public bool HasHomeDelivery { get { return _hasHomeDelivery; } set { _hasHomeDelivery = value; } } public bool HasDineIn { get { return _hasDineIn; } set { _hasDineIn = value; } } public string ServiceAvailableFrom { get { return _serviceAvailableFrom; } set { _serviceAvailableFrom = value; } } public string ServiceAvailableTill { get { return _serviceAvailableTill; } set { _serviceAvailableTill = value; } } #endregion public Restaurant() { } } } For filling my class properties dynamically i have another class called MapperBase Class with following methods: public abstract class MapperBase<T> where T : new() { protected T Map(IDataRecord record) { T instance = new T(); string fieldName; PropertyInfo[] properties = typeof(T).GetProperties(); for (int i = 0; i < record.FieldCount; i++) { fieldName = record.GetName(i); foreach (PropertyInfo property in properties) { if (property.Name == fieldName) { property.SetValue(instance, record[i], null); } } } return instance; } public Collection<T> MapAll(IDataReader reader) { Collection<T> collection = new Collection<T>(); while (reader.Read()) { collection.Add(Map(reader)); } return collection; } } There is another class which inherits the SqlreaderBaseClass called DefaultSearch. Code is below public class DefaultSearch: SqlReaderBase<Restaurant> { protected override string commandText { get { return "Select Name from vw_Restaurants"; } } protected override CommandType commandType { get { return CommandType.Text; } } protected override Collection<IDataParameter> GetParameters(IDbCommand command) { Collection<IDataParameter> parameters = new Collection<IDataParameter>(); parameters.Clear(); return parameters; } protected override MapperBase<Restaurant> GetMapper() { MapperBase<Restaurant> mapper = new RMapper(); return mapper; } } But whenever I tried to build , I am getting error 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. Even T here is Restaurant has a Parameterless Public constructor.

    Read the article

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