my basic question is how to insert data into DB as a serialized object and how to extract and use it then ... any suggestion !!?
e.g :
{id:1, userId:1, type:PHOTO, time:2008-10-15 12:00:00, data:{photoId:2089, photoName:A trip to the beach}}
as you see how could I insert data into column Data and then to use it !?
another question is that if I stored the photoName inside Data instead of using JOINS and get the name from it's table (photos) according to it's Id thats will not implement the last update on the photoName (right !?) besides that I'll not be able to make a relation between table photos and the Current table - (Id => photoId) - if I stored data like that .. so part of the problem is that I don't know exactly what kind of information are going to be stored in colum Data So I can't customize a separate column for every type of these information ...
Typically I see two options for you here.
You can store an XML serialized object into the database, and simply use standard XML Serialization, here is an example that you can adapt for your needs.
You can create a true table for this object, and do things the "Standard" way.
With option 1, filtering/joining/searching on the information in the "data" column although still technically possible, is NOT something i would recommend and would be more for a static storage process in my opinion. Something like a user settings entity, or some other item that is VERY unlikely to be needed for a backend query.
With option 2, yes, you have to do more work, but if you define the object well, it will be possible.
Clarification
With regards to my example in #1 above. You would write out to a memory stream, etc for the serialization rather than a file.
If you don't want to store the data relationally, you're really better off not using a relational database. Several object databases speak JSON and would be able to handle this kind of problem pretty easily.
You can store it as JSON string and use JSONSerializer of JSON lib
http://json-lib.sourceforge.net/apidocs/index.html
to convert javabean into json string/object and vice versa.
Generally we use this to store the configuration where no of config parameters are unknown.
Regarding saving an object in your database; you can serialize your object into xml using XDocument.ToString() and save it in database's xml datatype column.
cmd.Parameters.AddWithValue("#Value", xmldoc.ToString());
Checkout, Work with XML Data Type in SQL Server
Related
The question:
Do you guys know if there is any way that I can put an object in the header of a DataTable column, instead of an integer or a string?
Further explanation:
I'm writing a library that, in some moment, will read data from different meteorological stations. The data I'll read will be, for example, temperature, wind speed, atmospheric pressure, etc. These values can be read in different units (km/h, mph, celsius, fahrenheit) and the information about these units will be in a separate source, not together with the data itself. I'll be reading a XML file that will contain all the information about this datafile and, what I wanted to do is create an object with different attributes and use this object as the header of each column of the DataTable. A bit complicated explanation but I think that I was clear enough.
Do you think that it is possible using native .NET types or, if I wanted to do exactly this way I'd have to create my own table class?
Thank you all!
There is a DataColumn.ExtendedProperties collection, which works like a dictionary and can hold any objects.
So every DataTable column can have an object associated with it, which have description of type, units and any other info.
Let me first describe the situation. We host many Alumni events over the course of each year and provide online registration forms for each event. There is a large chunk of data that is common for each event:
An Event with dates, times, managers, internal billing info, etc.
A Registration record with info about the payment and total amount charged per form submission
Bio/Demographic and alumni data about the 1 or more attendees (name, address, degree, etc.)
We store all of the above data within columns in tables as you would expect.
The trouble comes with the 'extra' fields we are asked to put on the forms. Maybe it is a dinner and there is a Veggie or Carnivore option, perhaps there is lodging and there are bed or smoking options, or perhaps there is an optional transportation option. There are tons of weird little "can you add this to the form?" types of requests we receive.
Currently, we JSONify any non-standard data and store it all in one column (per attendee) called 'extras'. We can read this data out in code but it is not well suited to querying. Our internal staff would like to generate a quick report on Veggie dinners needed for instance.
Other than creating a separate table for each form that holds the specific 'extra' data items, are there any other approaches that could make my life (and reporting) easier? Anyone working in a simialr environment?
This is actually one of the toughest problem to solve efficiently. The SQL Server Customer Advisory Team has dedicated a white-paper to the topic which I highly recommend you read: Best Practices for Semantic Data Modeling for Performance and Scalability.
You basically have 3 options:
semantic database (entity-attribute-value)
XML column
sparse columns
Each solution comes with ups and downs. Out of the top of my hat I'd say XML is probably the one that gives you the best balance of power and flexibility, but the optimal solution really depends on lots of factors like data set sizes, frequency at which new attributes are created, the actual process (human operators) that create-populate-use these attributes etc, and not at least your team skill set (some might fare better with an EAV solution, some might fare better with an XML solution). If the attributes are created/managed under a central authority and adding new attributes is a reasonable rare event, then the sparse columns may be a better answer.
Well you could also have the following db structure:
Have a table to store custom attributes
AttributeID
AttributeName
Have a mapping table between events and attributes with:
AttributeID
EventID
AttributeValue
This means you will be able to store custom information per event. And you will be able to reuse your attributes. You can include some metadata as
AttributeType
AllowBlankValue
to the attribute to handle it easily afterwards
Have you considered using XML instead of JSON? Difference: XML is supported (special data type) and has query integration ;)
quick and dirty, but actually nice for querying: simply add new columns. it's not like the empty entries in the previous table should cost a lot.
more databasy solution: you'll have something like an event ID in your table. You can link this to an n:m table connecting events to additional fields. And then store the additional field data in a table with additional_field_id, record_id (from the original table) and the actual value. Probably creates ugly queries, but seems politically correct in terms of database design.
I understand "NoSQL" (not only sql ;) databases like couchdb let you store arbitrary fields per record, but since you're already with SQL Server, I guess that's not an option.
This is the solution that we first proposed in ASP.NET Forums (that later became Community Server), and that the ASP.NET team built a similar version of in the ASP.NET 2.0 Membership when they released it:
Property Bags on your domain objects
For example:
Event.Profile() or in your case, Event.Extras().
Basically, a property bag is a serialized collection of data stored in a name/value pair in a column (or columns). The ASP.NET 2.0 Membership went the route of storing names in a semi-colon delimited list, and values in the same:
Table: aspnet_Profile
Column: PropertyNames (separated by semi-colons, and has start index and end index)
Column: PropertyValues (separated by semi-colons, and only stores the string value)
The downside to that approach is it is all strings, and manually has to be parsed (even though the membership system does it for you automatically).
Recently, my current method is I've built FormCollection and NameValueCollection C# extension methods that automatically serialize the collections to an XML result. And I store that XML in the table in it's own column associated with that entity. I also have a deserializer C# extension on XElement that deserializes that data back to the collection at runtime.
This gives you the power of actually querying those properties in XML, via SQL (though, that can be slow though - always flatten out your read-only data).
The final note is runtime querying: The general rule we follow is, if you are going to query a property of an entity in normal application logic, then you move that property to an actual column on the table - and create the appropriate indexes. If that data will never be queried directly (for example, Linq-to-Sql or EF), then leave it in the XML Property Bag.
Property Bags gives you the power of extending your domain models however you like, without having to modify the db schema.
I'm writing this application that will allow a user to define custom quizzes and then allow another user to respond to the questions. Each question of the quiz has a corresponding datatype.
All the responses to all the questions are stored vertically in my [Response] table.
I currently use 2 fields to store the response.
//Response schema
ResponseID int
QuizPersonID int
QuestionID int
ChoiceID int //maps to Choice table, used for drop down lists
ChoiceValue varbinary(MAX) //used to store a user entered value
I'm using .net 3.5 C# SQL Server 2008.
I'm thinking that I would want to store different datatypes in the same field and then in my SQL report proc I would CONVERT to the proper datatype. I'm thinking this is ideal because I only have to check one field. I'm also thinking it might be more trouble than it is worth.
I think my other options are to; store the data as strings in the db (yuck), or to have a column for each datatype I might use.
So what I would like to know is, how would I format my datatypes in C# so that they can be converted properly in SQL? What is the performance hit for converting in SQL? Should I just make a whole wack of columns for each datatype?
Still not a perfect solution but you might like to take a look at the sql_variant data type which allows you to store most SQL Server types in the same column. But note that "long" data is not supported.
An alternative that I've also used in similar situations in the past is to have a separate table for each type of response along with the "parent" response table. This aso allows you to properly relate to your choice table. For example, you would have the following tables:
Response
StringResponse
DateTimeResponse
BitResponse
ChoiceResponse
XyzResponse, etc
All the typed response tables would be in an optional 1-1 relationship with Response and all other relating tables would relate to the parent Response table only.
We are communicating with a 3rd party service using via an XML file based on standards that this 3rd party developed. They give us an XML template for each "transaction" and we read it into a DataSet using System.Data.DataSet.ReadXML, set the proper values in the DataSet, and then write the XML back using System.Data.DataSet.WriteXML. This process has worked for several different files. However, I am now adding an additional file which requires that an integer data type be set on one of the fields. Here is a scaled down version:
<EngineDocList>
<DocVersion>1.0</DocVersion>
<EngineDoc>
<MyData>
<FieldA></FieldA>
<FieldB></FieldB>
<ClientID DataType="S32"></ClientID>
</MyData>
</EngineDoc>
</EngineDocList>
When I look at the DataSet created by my call to ReadXML to this file, the MyData table has columns of FieldA, FieldB, and MyData_ID. If I then set the value of MyData_ID and then make the call to WriteXML, the export XML has no value for ClientID. Once again, if I take a way the DataType, then I do have a ClientID column, I can set it properly, and the exported XML has the proper value. However, the third party requires that this data type be defined.
Any thoughts on why the ReadXML would be renaming this tag or how I could otherwise get this process to work? Alternatively, I could revamp the way we are reading and writing the XML, but would obviously rather not go down this path although these suggestions would also be welcome. Thanks.
I would not do this with a DataSet. It has a specific focus on simulating a relational model. Much XML will not follow that model. When the DataSet sees things that don't match it's idea of the world, it either ignores them or changes them. In neither case is it a good thing.
I'd use an XmlDocument for this.
I have an order which has a status (which in code is an Enum). The question is how to persist this. I could:
Persist the string in a field and then map back to enum on data retrieval.
Persist this as an integer and then map back to enum on data retrieval.
Create separate table for enum value and do a join on data retrieval.
Thoughts?
If this is a fixed list (which it seems it is, or else you shouldn't store it as an enum), I wouldn't use #1.
The main reason to use #3 over #2 is for ease of use with self-service querying utilities. However, I'd actually go with a variant of #2: Store the value as an integer and map to an enum on data retrieval. However, also create a table representing the enum type, with the value as the PK and the name as another column. That way it's simple, quick, and efficient to use with your code, but also easy to get the logical value with self-service querying and other uses that don't use your data access code.
#3 is the most "proper" from a database/normalization standpoint. Your status is, in effect, a domain entity that's linked to the order entity.
hibernate uses integers by default.
if your enum is not going to change very often, this is not a bad idea, i think.
I'd use an integer mapped to value in another table with the values.
You could also then map the enum to the same value, but then you'd have to update in both spots.
I suppose it depends on where the data will be retrieved. With #3, you could retrieve the data without relying on your .NET front end. But it is also possible for your database table to get out of sync with the enum code.
Option #2 is certainly the most efficient way to do it for storage... but storage is cheap.