Search Results

Search found 6149 results on 246 pages for 'concept mapping'.

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

  • One to many in nhibernate mapping problem

    - by chobo2
    Hi I have this using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo.Framework.Domain { public class UserEntity { public virtual Guid UserId { get; protected set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TDemo.Framework.Domain { public class Users : UserEntity { public virtual string OpenIdIdentifier { get; set; } public virtual string Email { get; set; } public virtual IList<Movie> Movies { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo.Framework.Domain { public class Movie { public virtual int MovieId { get; set; } public virtual Guid UserId { get; set; } // not sure if I should inherit UserEntity public virtual string Title { get; set; } public virtual DateTime ReleaseDate { get; set; } // in my ms sql 2008 database I want this to be just a Date type. Not sure how to do that. public virtual int Upc { get; set; } } } <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Demo.Framework" namespace="Demo.Framework.Domain"> <class name="Users"> <id name="UserId"> <generator class="guid.comb" /> </id> <property name="OpenIdIdentifier" not-null="true" /> <property name="Email" not-null="true" /> </class> <subclass name="Movie"> <list name="Movies" cascade="all-delete-orphan"> <key column="MovieId" /> <index column="MovieIndex" /> // not sure what index column is really. <one-to-many class="Movie"/> </list> </subclass> </hibernate-mapping> <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Demo.Framework" namespace="Demo.Framework.Domain"> <class name="Movie"> <id name="MovieId"> <generator class="native" /> </id> <property name="Title" not-null="true" /> <property name="ReleaseDate" not-null="true" type="Date" /> <property name="Upc" not-null="true" /> <property name="UserId" not-null="true" type="Guid"/> </class> </hibernate-mapping> I get this error 'extends' attribute is not found or is empty. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: NHibernate.MappingException: 'extends' attribute is not found or is empty. Source Error: Line 17: { Line 18: Line 19: var nhConfig = new Configuration().Configure(); Line 20: var sessionFactory = nhConfig.BuildSessionFactory(); Line 21:

    Read the article

  • Automatic layout of manual network mapping

    - by Paul
    So I have a small business network mainly consisting of two routed layer-2 domains with a total of ca. 100 devices spread over ca. 2000m² production and office spaces. Typical problems to solve using the graph would be: Over what (cable) path is a PC connected to the server? Where to expect devices connected to a switch port? I want to generate a graph of the physical network topology: Nodes are endpoint devices, switch ports, wall outlets, patch panel ports etc. Edges are cable connections. Ideally, grouping edges (or segments) that pass through the same bundle could be grouped. Also I would like to augment the graph data with automatically gathered data (monitoring state, MAC address, Switch port <- MAC entries to build up parts of the map). At the moment I use graphviz for this inside a Confluence wiki like that: layout = "neato" overlap = scale subgraph { rankdir = "TB" subgraph cluster_r1pf1 { r1pf1 [label="{ Rack 1 PF 1 | { <p1>P1 | <p2>P2 | <p3>P3} }", shape=record] } subgraph cluster_switch1 { switch1 [label="{ Rack 1 Switch 1 | { <p1> P1 | <p1> P1 | <p3> P3} }", shape=record] } r1pf1:p1 -> switch1:p1 (obviously there are dozens of entries omitted here) Problem is: I have a hard time to influence graphviz to generate a bearable layout. Edges overlap so bad that you can't read the diagram anymore. The question is: What other tools (be it interactive like Visio, Omnigraffle or I/O-oriented like graphviz) exist that would allow an easily versionable (as in: Operates on a text file) documentation that is both machine and human readable and editable? Why not OmniGraffle or Visio? Well we don't have Macs and Visio is not available at the moment. To buy it I would need good arguments. Automation would be one of that. But last time I looked, versioning Visio files or even thinking about automatic handling was a nightmare. Related: Network Mapping Tools basically asks the same with a focus on generating the complete graph automatically (but without the need to document cabling connections) Recommendations for automatic computer inventory brings up links of "all-in-one" solutions

    Read the article

  • Mapping tables from an existing database to an object -- is Hibernate suited?

    - by Bernhard V
    Hello! I've got some tables in an existing database and I want to map them to a Java object. Actually it's one table that contains the main information an some other tables that reference to such a table entry with a foreign key. I don't want to store objects in the database, I only want to read from it. The program should not be allowed to apply any changes to the underlying database. Currently I read from the database with 5 JDBC sql queries and set the results then on an object. I'm now looking for a less code intensive way. Another goal is the learning aspect. Is Hibernate suitable for this task, or is there another ORM framework that better fits my requirement?

    Read the article

  • Inherited fluent nhibenate mapping issue

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

    Read the article

  • Dozer deep mapping not working

    - by user363900
    I am trying to use dozer to map between classes. I have a source class that looks like this: public class initRequest{ protected String id; protected String[] details } I have a destination class that looks like this: public class initResponse{ protected String id; protected DetailsObject detObj; } public class DetailsObject{ protected List<String> details; } So essentially i want the string in the details array to be populated into the List in the Details object. I have tried a mapping like this: <mapping wildcard="true" > <class-a>com.starwood.valhalla.sgpms.dto.InitiateSynchronizationDTO</class-a> <class-b>com.starwood.valhalla.psi.sgpms.dto.InitiateSynchronizationDTO</class-b> <field> <a is-accessible="true">reservations</a> <b is-accessible="true">reservations.confirmationNum</b> </field> </mapping> But I get this error: Exception in thread "main" net.sf.dozer.util.mapping.MappingException: java.lang.NoSuchFieldException: reservations.confirmationNum at net.sf.dozer.util.mapping.util.MappingUtils.throwMappingException(MappingUtils.java:91) at net.sf.dozer.util.mapping.propertydescriptor.FieldPropertyDescriptor.<init>(FieldPropertyDescriptor.java:43) at net.sf.dozer.util.mapping.propertydescriptor.PropertyDescriptorFactory.getPropertyDescriptor(PropertyDescriptorFactory.java:53) at net.sf.dozer.util.mapping.fieldmap.FieldMap.getDestPropertyDescriptor(FieldMap.java:370) at net.sf.dozer.util.mapping.fieldmap.FieldMap.getDestFieldType(FieldMap.java:103) at net.sf.dozer.util.mapping.util.MappingsParser.processMappings(MappingsParser.java:95) at net.sf.dozer.util.mapping.util.CustomMappingsLoader.load(CustomMappingsLoader.java:77) at net.sf.dozer.util.mapping.DozerBeanMapper.loadCustomMappings(DozerBeanMapper.java:149) at net.sf.dozer.util.mapping.DozerBeanMapper.getMappingProcessor(DozerBeanMapper.java:132) at net.sf.dozer.util.mapping.DozerBeanMapper.map(DozerBeanMapper.java:94) at com.starwood.valhalla.mte.translator.StarguestPMSIntegrationDozerAdapter.adaptInit(StarguestPMSIntegrationDozerAdapter.java:30) How can i map this so that it works?

    Read the article

  • Design for XML mapping scenarios between two different systems [on hold]

    - by deepak_prn
    Mapping XML fields between two systems is a mundane routine in integration scenarios. I am trying to make the design documents look better and provide clear understanding to the developers especially when we do not use XSLT or any other IDE such as jDeveloper or eclipse plugins. I want it to be a high level design but at the same time talk in developer's language. So that there is no requirements that slip under the crack. For example, one of the scenarios goes: the store cashier sells an item, the transaction data is sent to Data management system. Now, I am writing a functional design for the scenario which deals with mapping XML fields between our system and the data management system. Question : I was wondering if some one had to deal with mapping XML fields between two systems? (without XSLT being involved) and if you used a table to represent the fields mapping (example is below) or any other visualization tool which does not break the bank ? I am trying to find out if there is a better way to represent XML mapping in your design documents. The widely accepted and used method seems to be using a simple table such as in the picture to illustrate the mapping. I am wondering if there are alternate ways/ tools to represent such as in Altova:

    Read the article

  • Nhibernate, mapping as (n)varchar max ?

    - by Quandary
    Question: In nHiberne, I map a string like this: [NHibernate.Mapping.Attributes.Property(Name = "MLST_Description", Type = "String", Length = 400)] which maps string to nvarchar(400) This one [NHibernate.Mapping.Attributes.Property(Name = "MLST_Description", Type = "String")] maps to nvarchar(255) But how can I map to nvarchar(max) ?

    Read the article

  • Hibernate mapping to object that already exists

    - by teehoo
    I have two classes, ServiceType and ServiceRequest. Every ServiceRequest must specify what kind of ServiceType it is. All ServiceType's are predefined in the database, and ServiceRequest is created at runtime by the client. Here are my .hbm files: <hibernate-mapping> <class dynamic-insert="false" dynamic-update="false" mutable="true" name="xxx.model.entity.ServiceRequest" optimistic-lock="version" polymorphism="implicit" select-before-update="false"> <id column="USER_ID" name="id"> <generator class="native"/> </id> <property name="quantity"> <column name="quantity" not-null="true"/> </property> <many-to-one cascade="all" class="xxx.model.entity.ServiceType" column="service_type" name="serviceType" not-null="false" unique="false"/> </class> </hibernate-mapping> and <hibernate-mapping> <class dynamic-insert="false" dynamic-update="false" mutable="true" name="xxx.model.entity.ServiceType" optimistic-lock="version" polymorphism="implicit" select-before-update="false"> <id column="USER_ID" name="id"> <generator class="native"/> </id> <property name="description"> <column name="description" not-null="false"/> </property> <property name="cost"> <column name="cost" not-null="true"/> </property> <property name="enabled"> <column name="enabled" not-null="true"/> </property> </class> </hibernate-mapping> When I run this, I get com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails I think my problem is that when I create a new ServiceRequest object, ServiceType is one of its properties, and therefore when I'm saving ServiceRequest to the database, Hibernate attempts to insert the ServiceType object once again, and finds that it is already exists. If this is the case, how do I make it so that Hibernate points to the exists ServiceType instead of trying to insert it again?

    Read the article

  • keyboard key mapping gone haywire

    - by arvind
    I have a Sony VGN-CR353 running Windows 7 Ultimate. For typing purposes I use two keyboards: The Inbuilt Laptop Keyboard A Standard External Desktop Grade USB Keyboard Since yesterday, My inbuilt keyboard's keys have gone all awry. This is Similar to http://superuser.com/questions/11537/keyboard-keys-not-working-or-resulting-in-the-wrong-key But the high point is that the external keyboard is working just fine. I have already tried System Restore, Reinstalling Keyboard Drivers etc. but to no avail. This is really bugging. Please Help. Thanks in Advance.

    Read the article

  • net use mapping not working in batch files but works in cmd

    - by Philippe
    Ok so here's the problem : I've got users using logon script in the domain (username.bat). The script simply lists 4 or 5 (net use letter: \\SERVER\directory\). However, when they open their session, the logon script doesnt work and returns system error 53 or 67 for all of them. I tried running the script after the profile has loaded and evrything is running, and it still gives me the error. I've then tried to run the same command in the cmd.exe. Everything mapped correctly. It also works fine if I map the drives using the "Tools Map network drives" utility. Is there anything that can prevent a command to work when ran in a batch-file but works correctly when typed in manually?

    Read the article

  • Mapping Super+hjkl to arrow keys under X

    - by Bill Casarin
    I'm trying to map: Super+h -> Left Super+j -> Down Super+k -> Up Super+l -> Right globally under X. The idea is I don't want to leave my home row that often to use the arrow keys, so I'll use the Super modifier + hjkl to emulate the arrow keys under X. Is there any way to do this? One thing I've tried is xbindkeys + xte using this configuration: "xte 'keydown Up' 'keyup Up'" Mod4+k "xte 'keydown Down' 'keyup Down'" Mod4+j "xte 'keydown Left' 'keyup Left'" Mod4+h "xte 'keydown Right' 'keyup Right'" Mod4+l but there seems to a large delay between me pressing the key and noticing any result, and most of the time nothing happens at all. Is there a more elegant way of doing this that actually works with no delay?

    Read the article

  • Routing and Remote Access Port Mapping not applied to localhost

    - by Computer Guru
    Hi, I've set up Routing and Remote Access (Windows Server 2003) to forward publicip:80 to a server on the private internal network, and that's working great. Incoming requests from the internet to port 80 are correctly forwarded to our internal web server and everything is fine. However, requests on the server itself are not being forwarded. That is, if I open a console window and type "telnet publicip 80" from the server on publicip, the request is not forwarded to the private server. I understand that in RRAS I've mapped port 80 on the public interface to the private server and that's why it's not working; but I don't know how to configure it so that requests from the local PC are also forwarded to the private server. I'd appreciate any help or feedback on the matter. Thanks!

    Read the article

  • Dependency diagramming / mapping tool [closed]

    - by Lars
    I am looking for a tool that allows me to easily create and maintain dependency maps of our mission critical servers, apps, processes, etc. It needs to be intuitive and easy to work with and be able to generate diagrams that clearly show the dependencies graphically. What would be some good tools for this? I have looked at videos for AssetGen Sysmap and BluePrint from Pathwaysystems.com, and they both seem to fit my needs, but there has got to be more good systems like them that I can look at. I want to make sure I pick the best system for our needs (and limited budget).

    Read the article

  • HasMany relation inside a Join Mapping

    - by Sean McMillan
    So, I'm having a problem mapping in fluent nhibernate. I want to use a join mapping to flatten an intermediate table: Here's my structure: [Vehicle] VehicleId ... [DTVehicleValueRange] VehicleId DTVehicleValueRangeId AverageValue ... [DTValueRange] DTVehicleValueRangeId RangeMin RangeMax RangeValue Note that DTValueRange does not have a VehicleID. I want to flatten DTVehicleValueRange into my Vehicle class. Tgis works fine for AverageValue, since it's just a plain value, but I can't seem to get a ValueRange collection to map correctly. public VehicleMap() { Id(x => x.Id, "VehicleId"); Join("DTVehicleValueRange", x => { x.Optional(); x.KeyColumn("VehicleId"); x.Map(y => y.AverageValue).ReadOnly(); x.HasMany(y => y.ValueRanges).KeyColumn("DTVehicleValueRangeId"); // This Guy }); } The HasMany mapping doesn't seem to do anything if it's inside the Join. If it's outside the Join and I specify the table, it maps, but nhibernate tries to use the VehicleID, not the DTVehicleValueRangeId. What am I doing wrong?

    Read the article

  • NHibernate: Mapping multiple classes from a single table row

    - by Michael Kurtz
    I couldn't find an answer to this specific question. I am trying to keep my domain model object-oriented and re-use objects where possible. I am having an issue determining how to provide a mapping to multiple classes from a single row. Let me explain with an example: I have a single table, call it Customer. A customer has several attributes; but, for brevity, assume it has Id, Name, Address, City, State, ZipCode. I would like to create a Customer and Address class that look like this: public class Customer { public virtual long Id {get;set;} public virtual string Name {get;set;} public virtual Address Address {get;set;} } public class Address { public virtual string Address {get;set;} public virtual string City {get;set;} public virtual string State {get;set;} public virtual string ZipCode {get;set;} } What I am having trouble with is determining what the mapping would be for the Address class within the Customer class. There is no Address table and there isn't a "set" of addresses associated with a Customer. I just want a more object-oriented view of the Customer table in code. There are several other tables that have address information in them and it would be nice to have a reusable Address class to deal with them. Addresses are not shared so breaking all addresses into a separate table with foreign keys seems to be overkill and, actually, more painful since I would need foreign keys to multiple tables. Can someone enlighten me on this type of mapping? Please provide an example if you can. Thanks for any insights! -Mike

    Read the article

  • Spring URL mapping question

    - by es11
    I am using Java with Spring framework. Given the following url: www.mydomain.com/contentitem/234 I need to map all requests that come to /contentitem/{numeric value} mapped to a given controller with the "numeric value" passed as a parameter to the controller. Right now in my servlet container xml I have simple mappings similar to the following: ... <entry key="/index.html"> <ref bean="homeController" /> </entry> ... I am just wondering what I need to add to the mapping in order to achieve what I described? Edit: I unaccepted the answer temporarily because I can't seem to figure out how to do the mapping in my web.xml (I am using annotations as described in axtavt's answer below). How do I add a proper <url-pattern>..</url-pattern> in my <servlet-mapping> so that the request for "/contentitem/{numeric_value}" gets properly picked up? Thanks!

    Read the article

  • Strategies for Mapping Views in NHibernate

    - by Nathan Fisher
    It seems that NHibernate needs to have an id tag specified as part of the mapping. This presents a problem for views as most of the time (in my experience) a view will not have an Id. I have mapped views before in nhibernate, but they way I did it seemed to be be messy to me. Here is a contrived example of how I am doing it currently. Mapping <class name="ProductView" table="viewProduct" mutable="false" > <id name="Id" type="Guid"> <generator class="guid.comb" /> </id> <property name="Name" /> <!-- more properties --> </class> View SQL Select NewID() as Id, ProductName as Name, --More columns From Product Class public class ProductView { public virtual Id {get; set;} public virtual Name {get; set;} } I don't need an Id for the product or in the case of some views I may not have an id for the view, depending on if I have control over the View Is there a better way of mapping views to objects in nhibernate?

    Read the article

  • Return value mapping on Stored Procedures in Entity Framework

    - by Yucel
    Hi, I am calling a stored procedure with EntityFramework. But custom property that i set in partial entity class is null. I have Entities in my edmx (I called edmx i dont know what to call for this). For example I have a "User" table in my database and so i have a "User" class on my Entity. I have a stored procedure called GetUserById(@userId) and in this stored procedure i am writing a basic sql statement like below "SELECT * FROM Users WHERE Id=@userId" in my edmx i make a function import to call this stored procedure and set its return value to Entities (also select User from dropdownlist). It works perfectly when i call my stored procedure like below User user = Context.SP_GetUserById(123456); But i add a custom new column to stored procedure to return one more column like below SELECT *, dbo.ConcatRoles(U.Id) AS RolesAsString FROM membership.[User] U WHERE Id = @id Now when i execute it from SSMS new column called RolesAsString appear in result. To work this on entity framework i added a new property called RolesAsString to my User class like below. public partial class User { public string RolesAsString{ get; set; } } But this field isnt filled by stored procedure when i call it. I look to the Mapping Detail windows of my SP_GetUserById there isnt a mapping on this window. I want to add but window is read only i cant map it. I looked to the source of edmx cant find anything about mapping of SP. How can i map this custom field?

    Read the article

  • Spring Controller's URL request mapping not working as expected

    - by Atharva
    I have created a mapping in web.xml something like this: <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/about/*</url-pattern> </servlet-mapping> In my controller I have something like this: import org.springframework.stereotype.Controller; @Controller public class MyController{ @RequestMapping(value="/about/us", method=RequestMethod.GET) public ModelAndView myMethod1(ModelMap model){ //some code return new ModelAndView("aboutus1.jsp",model); } @RequestMapping(value="/about", method=RequestMethod.GET) public ModelAndView myMethod2(ModelMap model){ //some code return new ModelAndView("aboutus2.jsp",model); } } And my dispatcher-servlet.xml has view resolver like: <mvc:annotation-driven/> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/> To my surprise: request .../about/us is not reaching to myMethod1 in the controller. The browser shows 404 error. I put a logger inside the method but it isn't printing anything, meaning, its not being executed. .../about works fine! What can be the done to make .../about/us request work? Any suggestions?

    Read the article

  • Mapping many-to-many association table with extra column(s)

    - by user635524
    My database contains 3 tables: User and Service entities have many-to-many relationship and are joined with the SERVICE_USER table as follows: USERS - SERVICE_USER - SERVICES SERVICE_USER table contains additional BLOCKED column. What is the best way to perform such a mapping? These are my Entity classes @Entity @Table(name = "USERS") public class User implements java.io.Serializable { private String userid; private String email; @Id @Column(name = "USERID", unique = true, nullable = false,) public String getUserid() { return this.userid; } .... some get/set methods } @Entity @Table(name = "SERVICES") public class CmsService implements java.io.Serializable { private String serviceCode; @Id @Column(name = "SERVICE_CODE", unique = true, nullable = false, length = 100) public String getServiceCode() { return this.serviceCode; } .... some additional fields and get/set methods } I followed this example http://giannigar.wordpress.com/2009/09/04/m ... using-jpa/ Here is some test code: User user = new User(); user.setEmail("e2"); user.setUserid("ui2"); user.setPassword("p2"); CmsService service= new CmsService("cd2","name2"); List<UserService> userServiceList = new ArrayList<UserService>(); UserService userService = new UserService(); userService.setService(service); userService.setUser(user); userService.setBlocked(true); service.getUserServices().add(userService); userDAO.save(user); The problem is that hibernate persists User object and UserService one. No success with the CmsService object I tried to use EAGER fetch - no progress Is it possible to achieve the behaviour I'm expecting with the mapping provided above? Maybe there is some more elegant way of mapping many to many join table with additional column?

    Read the article

  • Inheritance Mapping Strategies with Entity Framework Code First CTP5 Part 1: Table per Hierarchy (TPH)

    - by mortezam
    A simple strategy for mapping classes to database tables might be “one table for every entity persistent class.” This approach sounds simple enough and, indeed, works well until we encounter inheritance. Inheritance is such a visible structural mismatch between the object-oriented and relational worlds because object-oriented systems model both “is a” and “has a” relationships. SQL-based models provide only "has a" relationships between entities; SQL database management systems don’t support type inheritance—and even when it’s available, it’s usually proprietary or incomplete. There are three different approaches to representing an inheritance hierarchy: Table per Hierarchy (TPH): Enable polymorphism by denormalizing the SQL schema, and utilize a type discriminator column that holds type information. Table per Type (TPT): Represent "is a" (inheritance) relationships as "has a" (foreign key) relationships. Table per Concrete class (TPC): Discard polymorphism and inheritance relationships completely from the SQL schema.I will explain each of these strategies in a series of posts and this one is dedicated to TPH. In this series we'll deeply dig into each of these strategies and will learn about "why" to choose them as well as "how" to implement them. Hopefully it will give you a better idea about which strategy to choose in a particular scenario. Inheritance Mapping with Entity Framework Code FirstAll of the inheritance mapping strategies that we discuss in this series will be implemented by EF Code First CTP5. The CTP5 build of the new EF Code First library has been released by ADO.NET team earlier this month. EF Code-First enables a pretty powerful code-centric development workflow for working with data. I’m a big fan of the EF Code First approach, and I’m pretty excited about a lot of productivity and power that it brings. When it comes to inheritance mapping, not only Code First fully supports all the strategies but also gives you ultimate flexibility to work with domain models that involves inheritance. The fluent API for inheritance mapping in CTP5 has been improved a lot and now it's more intuitive and concise in compare to CTP4. A Note For Those Who Follow Other Entity Framework ApproachesIf you are following EF's "Database First" or "Model First" approaches, I still recommend to read this series since although the implementation is Code First specific but the explanations around each of the strategies is perfectly applied to all approaches be it Code First or others. A Note For Those Who are New to Entity Framework and Code-FirstIf you choose to learn EF you've chosen well. If you choose to learn EF with Code First you've done even better. To get started, you can find a great walkthrough by Scott Guthrie here and another one by ADO.NET team here. In this post, I assume you already setup your machine to do Code First development and also that you are familiar with Code First fundamentals and basic concepts. You might also want to check out my other posts on EF Code First like Complex Types and Shared Primary Key Associations. A Top Down Development ScenarioThese posts take a top-down approach; it assumes that you’re starting with a domain model and trying to derive a new SQL schema. Therefore, we start with an existing domain model, implement it in C# and then let Code First create the database schema for us. However, the mapping strategies described are just as relevant if you’re working bottom up, starting with existing database tables. I’ll show some tricks along the way that help you dealing with nonperfect table layouts. Let’s start with the mapping of entity inheritance. -- The Domain ModelIn our domain model, we have a BillingDetail base class which is abstract (note the italic font on the UML class diagram below). We do allow various billing types and represent them as subclasses of BillingDetail class. As for now, we support CreditCard and BankAccount: Implement the Object Model with Code First As always, we start with the POCO classes. Note that in our DbContext, I only define one DbSet for the base class which is BillingDetail. Code First will find the other classes in the hierarchy based on Reachability Convention. public abstract class BillingDetail  {     public int BillingDetailId { get; set; }     public string Owner { get; set; }             public string Number { get; set; } } public class BankAccount : BillingDetail {     public string BankName { get; set; }     public string Swift { get; set; } } 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; } } This object model is all that is needed to enable inheritance with Code First. If you put this in your application you would be able to immediately start working with the database and do CRUD operations. Before going into details about how EF Code First maps this object model to the database, we need to learn about one of the core concepts of inheritance mapping: polymorphic and non-polymorphic queries. Polymorphic Queries LINQ to Entities and EntitySQL, as object-oriented query languages, both support polymorphic queries—that is, queries for instances of a class and all instances of its subclasses, respectively. For example, consider the following query: IQueryable<BillingDetail> linqQuery = from b in context.BillingDetails select b; List<BillingDetail> billingDetails = linqQuery.ToList(); Or the same query in EntitySQL: string eSqlQuery = @"SELECT VAlUE b FROM BillingDetails AS b"; ObjectQuery<BillingDetail> objectQuery = ((IObjectContextAdapter)context).ObjectContext                                                                          .CreateQuery<BillingDetail>(eSqlQuery); List<BillingDetail> billingDetails = objectQuery.ToList(); linqQuery and eSqlQuery are both polymorphic and return a list of objects of the type BillingDetail, which is an abstract class but the actual concrete objects in the list are of the subtypes of BillingDetail: CreditCard and BankAccount. Non-polymorphic QueriesAll LINQ to Entities and EntitySQL queries are polymorphic which return not only instances of the specific entity class to which it refers, but all subclasses of that class as well. On the other hand, Non-polymorphic queries are queries whose polymorphism is restricted and only returns instances of a particular subclass. In LINQ to Entities, this can be specified by using OfType<T>() Method. For example, the following query returns only instances of BankAccount: IQueryable<BankAccount> query = from b in context.BillingDetails.OfType<BankAccount>() select b; EntitySQL has OFTYPE operator that does the same thing: string eSqlQuery = @"SELECT VAlUE b FROM OFTYPE(BillingDetails, Model.BankAccount) AS b"; In fact, the above query with OFTYPE operator is a short form of the following query expression that uses TREAT and IS OF operators: string eSqlQuery = @"SELECT VAlUE TREAT(b as Model.BankAccount)                       FROM BillingDetails AS b                       WHERE b IS OF(Model.BankAccount)"; (Note that in the above query, Model.BankAccount is the fully qualified name for BankAccount class. You need to change "Model" with your own namespace name.) Table per Class Hierarchy (TPH)An entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented by a particular row is identified by the value of a type discriminator column. You don’t have to do anything special in Code First to enable TPH. It's the default inheritance mapping strategy: This mapping strategy is a winner in terms of both performance and simplicity. It’s the best-performing way to represent polymorphism—both polymorphic and nonpolymorphic queries perform well—and it’s even easy to implement by hand. Ad-hoc reporting is possible without complex joins or unions. Schema evolution is straightforward. Discriminator Column As you can see in the DB schema above, Code First has to add a special column to distinguish between persistent classes: the discriminator. This isn’t a property of the persistent class in our object model; it’s used internally by EF Code First. By default, the column name is "Discriminator", and its type is string. The values defaults to the persistent class names —in this case, “BankAccount” or “CreditCard”. EF Code First automatically sets and retrieves the discriminator values. TPH Requires Properties in SubClasses to be Nullable in the Database TPH has one major problem: Columns for properties declared by subclasses will be nullable in the database. For example, Code First created an (INT, NULL) column to map CardType property in CreditCard class. However, in a typical mapping scenario, Code First always creates an (INT, NOT NULL) column in the database for an int property in persistent class. But in this case, since BankAccount instance won’t have a CardType property, the CardType field must be NULL for that row so Code First creates an (INT, NULL) instead. If your subclasses each define several non-nullable properties, the loss of NOT NULL constraints may be a serious problem from the point of view of data integrity. TPH Violates the Third Normal FormAnother important issue is normalization. We’ve created functional dependencies between nonkey columns, violating the third normal form. Basically, the value of Discriminator column determines the corresponding values of the columns that belong to the subclasses (e.g. BankName) but Discriminator is not part of the primary key for the table. As always, denormalization for performance can be misleading, because it sacrifices long-term stability, maintainability, and the integrity of data for immediate gains that may be also achieved by proper optimization of the SQL execution plans (in other words, ask your DBA). Generated SQL QueryLet's take a look at the SQL statements that EF Code First sends to the database when we write queries in LINQ to Entities or EntitySQL. For example, the polymorphic query for BillingDetails that you saw, generates the following SQL statement: SELECT  [Extent1].[Discriminator] AS [Discriminator],  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift],  [Extent1].[CardType] AS [CardType],  [Extent1].[ExpiryMonth] AS [ExpiryMonth],  [Extent1].[ExpiryYear] AS [ExpiryYear] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] IN ('BankAccount','CreditCard') Or the non-polymorphic query for the BankAccount subclass generates this SQL statement: SELECT  [Extent1].[BillingDetailId] AS [BillingDetailId],  [Extent1].[Owner] AS [Owner],  [Extent1].[Number] AS [Number],  [Extent1].[BankName] AS [BankName],  [Extent1].[Swift] AS [Swift] FROM [dbo].[BillingDetails] AS [Extent1] WHERE [Extent1].[Discriminator] = 'BankAccount' Note how Code First adds a restriction on the discriminator column and also how it only selects those columns that belong to BankAccount entity. Change Discriminator Column Data Type and Values With Fluent API Sometimes, especially in legacy schemas, you need to override the conventions for the discriminator column so that Code First can work with the schema. The following fluent API code will change the discriminator column name to "BillingDetailType" and the values to "BA" and "CC" for BankAccount and CreditCard respectively: protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {     modelBuilder.Entity<BillingDetail>()                 .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue("BA"))                 .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue("CC")); } Also, changing the data type of discriminator column is interesting. In the above code, we passed strings to HasValue method but this method has been defined to accepts a type of object: public void HasValue(object value); Therefore, if for example we pass a value of type int to it then Code First not only use our desired values (i.e. 1 & 2) in the discriminator column but also changes the column type to be (INT, NOT NULL): modelBuilder.Entity<BillingDetail>()             .Map<BankAccount>(m => m.Requires("BillingDetailType").HasValue(1))             .Map<CreditCard>(m => m.Requires("BillingDetailType").HasValue(2)); SummaryIn this post we learned about Table per Hierarchy as the default mapping strategy in Code First. The disadvantages of the TPH strategy may be too serious for your design—after all, denormalized schemas can become a major burden in the long run. Your DBA may not like it at all. In the next post, we will learn about Table per Type (TPT) strategy that doesn’t expose you to this problem. 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

  • 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: Mapping an IDictionary<MappedClass, MyEnum>

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

    Read the article

  • Query regarding the Nhibernate many to many mapping

    - by Pramod
    Hi, I have a requirement where i have 3 dimension tables (employee, project, technology) and a common fact table which has the key id's of all these three tables. My question goes like this... How do i create a mapping table (fact table) having these three columns - emp_id, proj_i and tech_i. I know we can achieve this for two tables using the below syntax: HasManyToMany(x = x.Empl) .Table("Emp_Proj") .ParentKeyColumn("Emp_i") .ChildKeyColumn("Proj_I") .Inverse() .Cascade.All(); How can i add another child key column (tech_i) to the above mapping table?

    Read the article

  • Same table NHibernate mapping

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

    Read the article

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