Is there any ORM Framework which maps in another way than ActiveRecord pattern says? - database

There is commonly used method to map object to table (one object - one row in a table; the table is corresponding to object type), i.e., each object's public field is mapped to corresponding column in a table. Most of the ORM Frameworks are based on that mapping method. The question is there any ORM Framework (based on .Net Framework and well suited for C#) which allows to map object onto several rows in a table where each object's field is mapped to corresponding table's row?

I think what you're looking for is an ORM that generates Collection objects for each of your tables.
Look into Propel ORM
Any query that returns more than 1 row returns a TableObjectCollection object that has multiple convenient methods for access.

It is hard to say for all ORM Frameworks existing for today. But mapping in a following way:
(1) class type - table,
(2) class member/field - column of the table,
(3) class instance - row in a table,
is the well known practice. So, the more probable answer is there is no such ORM which maps a particular class instance on several rows. Otherwise, in accord with (2) the class type must has several members/fields represented with the same name but this is hardly possible.

Related

Database design to support dynamic entities

OK, I don't know whether this question belong to this place, but you will suggest me if I'm wrong.
I have some entities which has almost same attributes, differences is in maybe 2-3 columns.
Because of those different columns, I can't create one table with columns that are union of attributes of every entity, because new entity type will require changing table design adding new columns specific to that entity type.
Instead, currently working design is that every specific entity has own table.
But, if new type of entity come on scene, I must create new table, which is totally bad idea.
How can I create one table which consists shared attributes for each type of entity, and some additional mechanism to evidence entity-unique attributes?
So, idea is to easy add new types of objects, without changing database design, configuring only part that deal with unique columns.
P.S. Maybe I'm not clear, but I will add more description if is it needed.
I had a design like that once. What I did was I created a table that housed all the shared properties. Then, I had separate tables for the distinct values. I used joins to match a specific entity to its shared table row. I had less than 10, so my views that used unions I just updated when I added a new entity. But, if you used a naming convention, you could write stored procs that find the table names dynamically and do the unions and joins on the fly. In my case, I used a base class and specific classes to make a custom data layer.
Another possibility is to have a generic table that's basically name/value pairs and a table the represents your shared properties. By joining the tables together, you could have any number of entity specific properties for your entities. It's not very efficient and the SQL would get weird, but I've seen it done.
One solution is to store the common parts in one table, and the specific parts in tables specific to that entity.
eg: To have a set of people, some of whom are managers...
Person Table
PersonID
PersonName
Manager Table
ManagerID
PersonID
DepartmentManaged
As soon as you go down the path of having one table with variable field meanings - effectively an Entity Attribute Value design - you find yourself in querying hell.
Perhaps not the best or most academic, but what about this kind of "open structure" ?
MainTable: all common fields
SpecialProperties: extra properties, as required
- MainRecordId (P, F->MainTable)
- PropertyName (P)
- PropertyText
- PropertyValue (for numeric values)

Entity Attribute Value model (EAV) and how to achieve it with cfml?

I'm trying to figure out how to implement this relationship in coldfusion. Also if anyone knows the name for this kind of relationship I'd be curious to know it.
I'm trying to create the brown table.
Recreating the table from the values is not the problem, the problem that I've been stuck with for a couple of days now is how to create an editing environment.
I'm thinking that I should have a table with all the Tenants and TenantValues (TenantValues that match TenantID I'm editing) and have the empty values as well (the green table)
any other suggestions?
The name of this relationship is called an Entity Attribute Value model (EAV). In your case Tenant, TenantVariable, TenantValues are the entity, attribute and value tables, respectively. EAV is attempt to allow for the runtime definition or entities and is most found in my experience backing content managements systems. It has been referred to an as anti pattern database model because you lose certain RDBMS advantages, while gaining disadvantages such as having to lock several tables on delete or save. Often a suitable persistence alternative is a NoSQL solution such as Couch.
As for edits, the paradigm I typically see is deleting all the value records for a given ID and inserting inside a loop, and then updating the entity table record. Do this inside of a transaction to ensure consistency. The upshot of this approach is that it's must easier to figure out than delta detection algorithm. Another option is using the MERGE statement if your database supports it.
You may want to consider an RDF Triple Store for this problem. It's an alternative to Relational DBs that's particularly good for sparse categorical data. The data is represented as triples - directed graph edges consisting of a subject, an object, and the predicate that describes the property connecting them:
(subject) (predicate) (object)
Some example triples from your data set would look something like:
<Apple> rdf:type <Red_Fruit>
<Apple> hasWeight "1"^^xsd:integer
RDF triple stores provide the SPARQL query language to retrieve data from your store much like you would use SQL.

Linq-To-SQL Legacy Relation Mapping

I am trying to get Linq2SQL to work with my legacy database. I currently have a notes table that is generic to a few different entities and mapped m:m. Instead of mapping one relation table per entity type whoever designed this database decided to use a single relation table with a type column (as a varchar yuck!).
alt text http://img130.imageshack.us/img130/326/capturefm.png
How do I map Foo and Bar to have a Notes collection? Is this even possible. I am not seeing the light. I tried to have two classes FooNotes and BarNotes that inherit from RelateNotes and then mapping the Type field as the descriptor.
alt text http://img130.imageshack.us/img130/3153/capture2f.png
This doesn't work and I receive the below error.
Bad Storage property: '_EntityID' on member 'TestLinq.BarNotes.EntityID'.
I don't want to get too far down the Linq2SQL road before realising it not possible. I am not allowed to change the database much.
Many Thanks,
I would consider expanding your app's design to include a Domain Model based layered architecture.
This way you can create a Domain Model that meets the requirements of the system while abstracting away how the mapping works underneath. For example, you could have a common interface for the data access layer that returns the mapped entities. An implementation of this interface could be created for the old 'string-equality' m2m relationship in the legacy database. One day when you are ready to ditch the legacy database, a new implementation could be created for a different ER db model which would allow your Domain Model (object model) and higher layers (services, UI etc) to remain unchanged (because they all utilise the common interface).
In your object model you could define each object that needs Notes and have them each contain a Notes collection for each instance. Eg. Foo has a collection of Notes; Bar has a collection of Notes. Your Repository interface would look after returning these entities but the implementation of that repo would worry about how it's read and persisted to the db.

Singular data-keys between application and database?

Is there a paradigm in which I can change a data-key name in one place and one place only, and have it properly be dealt with by both the application and database?
I have resorted most recently to using class constants to map to database field names, but
I still have to keep those aligned with the raw database keys.
What I mean is, using PHP as an example, right now I might use
$infoToUpdateUser[ User::FIELD_FIRST_NAME ]
This means that when I change it at the constant, I don't have to search through the code to change all references to that field.
Another area this crops up in is in referencing fields. Due to some early poor design decisions, I have, for example, these sorts of tables:
( table name : primary_key )
cats : cat_id
dogs : dog_id
parrots : bird_id (remember, poor design, thus the mismatch between parrots / bird_id)
lizards: lizard_id
etc
Then let's say I have a series of form classes that update records.
AnimalForm
DogForm extends AnimalForm
CatForm extends AnimalForm
ParrotForm extends AnimalForm
etc
Now I want to update a record in the SQL database using an update function in the parent class, AnimalForm, so I don't have to replicate code in 20 subclasses.
However I do not know of a way to generalize the update query, so currently each subclass has an idFieldName member variable, and the parent class inserts that into the query, like
"UPDATE " . $this->table . " SET <data> WHERE " . $this->idFieldName
It seems sloppy to do it this way but I can't think of a better solution at this point.
Is there a design model or paradigm that links together or abstracts data-key names to be shared as a reference by both a database and an application?
What you are looking for is called an Object-Relational Mapping layer.
An ORM separates the concerns of data access from business logic by mapping a relational database into an object model. Since the ORM does all the translation, if you change the name of a database table or column, you only have to tell the ORM once, and it will properly apply that change to all of your code.
Since you indicate that you are using PHP, here is a question that addresses ORM libraries in PHP. Additional information about ORM technologies can be found in Wikipedia.

How to get my SQL DB to match my Domain Driven Design

Okay, I'll be straight with you guys: I'm not sure exactly how Domain Driven my Design is, but I did start by building Model objects and ignoring the persistence layer altogether. Now I'm having difficulty deciding the best way to build my tables in SQL Server to match the models.
I'm building a web application in ASP.NET MVC, although I don't think the platform matters that much. I have the following object model hierarchy:
Property - has properties such as Address and Postcode
which have one or more
Case - inherits from PropertyObject
Quote - inherits from PropertyObject
which have one or more
Message - simple class that has properties Reference, Text and SentDate
Case and Quote have a lot of similar properties, so I also have a PropertyObject abstract base class that they inherit from. So Property has an Items property of type List which can contain both Case and Quote objects.
So essentially, I can have a Property that has a few Quotes and Cases and a load of Messages that can belong to either of those.
A PropertyObject has a Reference property (and therefore so do Quote and Case) so any Message object can be related back to a Quote OR Case by it's Reference property.
I'm thinking of using the Entity Framework to get my Models in and out of the database.
My initial thoughts were to have four tables: Property, Case, Quote and Message.
They'd all have their own sequential IDs, and the Case and Quote would be related back to Property by a PropertyID field.
The only way I can think of to relate a Message table back to the Case and Quote tables is to have both a RelationID and RelationType field, but there's no obvious way to tell SQL server how that relationship works, so I won't have any referential integrity.
Any ideas, suggestions, help?
Thanks,
Anthony
I am assuming Property doesn't also inherit from PropertyObject.
Given that these tables, Property, Case, Quote and Message, leads to a Table per Concrete Class or TPC inheritance strategy, which I generally don't recommend.
My recommendation is that you use either:
Table per Hierarchy or TPH - Case and Quote are stored in the same table with one column used as a discriminator, with nullable columns for properties that are not shared.
Table per Type or TPT - add a PropertyObject table with the shared fields and Case and Quote tables with just the extra fields for those types
Both of these strategies will allow you to maintain referential integrity and are supported by most ORMs.
see this for more: Tip 12 - How to choose an inheritance strategy
Hope this helps
Alex
Ahhh... Abstraction.
The trick with DDD is to recognize that abstraction is not always your friend. In some cases, too much abstraction leads to a too-complex relational model.
You don't always need inheritance. Indeed, the major purpose of inheritance is to reuse code. Reusing a structure can be important, but less so.
You have a prominent is-a pair of relationships: Case IS-A Property and Quote IS-A Property.
You have several ways to implement class hierarchies and "is-a" relationships.
As you've suggested with type discriminators to show which subclass this really is. This works when you often have to produce a union of the various subclasses. If you need all properties -- a union of CaseProperty and QuoteProperty, then this can work out.
You do not have to rely on inheritance; you can have disjoint tables for each set of relationships. CaseProperty and QuoteProperty. You'd have CaseMessage and QuoteMessage also, to follow the distinction forward.
You can have common features in a common table, and separate features in a separate table, and do a join to reconstruct a single object. So you might have a Property table with common features of all properties, plus CaseProperty and QuoteProperty with unique features of each subclass of Property. This is similar to what you're proposing with Case and Quote having foreign keys to Property.
You can flatten a polymorphic class hierarchy into a single table and use a type discriminator and NULL's. A master Property table has type discriminator for Case and Quote. Attributes of Case are nulled for rows that are supposed to be a Quote. Similarly, attributes of Quote are nulled for rows that are supposed to be a Case.
Your question "[how] to relate a Message table back to the Case and Quote tables" stems from a polymorphic set of subclases. In this case, the best solution might be this.
Message has an FK reference to Property.
Property has a type discriminator to separate Quote from Case. The Quote and Case class definitions both map to Property, but rely on a type discriminator, and (usually) different sets of columns.
The point is that the responsibility for Property, CaseProperty and QuoteProperty belongs to that class hierarchy, and not Message.
This is where the DDD concept of Services would come in. The Repository for each of your concrete classes only persist that entity, not the related objects.
So you have Property(), and is the base for your CaseProperty() : Property(). This special-entity is accessed via CasePropertyService(). Within here is where you would do your JOINs and such to the related tables in order to generate your CaseProperty() special entity (which is not really Case() and Property on its own, but a combination).
OT: Due to limitation of .net of where you can't inherit multiple classes, this is my work around. DDD is meant to be a guideline to the overall understanding of your domain. I often give my DDD outline to friends, and have them try to figure out what it does/represent. If it looks clean and they figure it out, it's clean. If your friends look at it and say, "I have no idea what you are trying to persist here." then go back to the drawing board.
But, there's a catch about using any ORM to persist storage of DDD objects (linq, EntityFramework, etc). Have a look at my answer over here:
Stackoverflow: Question about Repositories and their Save methods for domain objects
The catch is all objects must have an identity in the database for ORM. So, this helps you plan your DB structure.
I have recently moved away from using ORM to control direct access, and just have a clean DDD layer. I let my repositories and services control access to the DB layer, and use Velocity to entity-cache my objects. This actually works very well for: 1) DB performance, you design however is most efficient not being coupled to your DOmain objects with direct ORM representation, and 2) your domain model becomes much cleaner with no forced identies on Value Objects and such. Free!

Resources