Question

It may be a little fancy but is there any pattern or something to store any kind of Object in Relational database (not nosql) in optimal way?

for example in none optimal way:

class Person{
    string FirstName {get;set;}
    string LastName {get;set;}
} 

class Product{
    string Name {get;set;}
    decimal Price {get;set;}
} 

and in database:

CREATE TABLE Data
   (Id int PRIMARY KEY, 
    TypeName nvarchar(50), 
    PropertyName nvarchar(50), 
    PropertyValue binary)

then records gets stored in database like this:

1    Person    FirstName   Jalal

2    Person    LastName    A.R

3    Product   Name        Apple

4    Product   Price       2
Was it helpful?

Solution

What you are describing is essentially an Entity-Attribute-Value table.

It is appropriately used in those cases where the number of potential attributes is large, but the number of potential values is small. An example of such a use case is medical data (symptoms), where the number of potential symptoms a patient can have is large, but the number of actual symptoms is small.

Improperly used, it is a classic example of Inner Platform Effect.

OTHER TIPS

You could serialize your object to XML, and store that in the database. SQL Server has a specialized XML type that will even allow you to query against the contents.

This is not an optimal solution, but it will do what you need.

Not sure why you would do this as hardly optimal. If looking for a person you would so a table scan/index lookup against a string value and then filter by primary key.

ORM's would be much much better- nHibernate or Entity Framework (EF) they will maps each class to a table and autogenerat eth primary keys etc and you can express the objects as child objects etc.

EF can also do code first - meaning you just write the classes and it will create the database and auto map them all up (nHibernate probably does as well, just i do not know product as well)

What you've described is not a relational approach, so I don't see why you want to use a relational database. You're lumping every single object into one big table. You completely lose the ability define relationships among tables or to perform relational operations (like "find all customers who bought an apple this month").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top