0

I am trying to store a C# class filled with properties and fields. How can I store that class into SQL Server 2008.

Can someone help??

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pravin Kumar
  • 1
  • 1
  • 1
  • 3
    Try looking at this link StackOverFlow http://stackoverflow.com/questions/1118296/c-how-would-you-store-arbitrary-objects-in-an-sql-server – MethodMan Aug 23 '12 at 16:34
  • try this http://stackoverflow.com/questions/1299410/can-i-save-an-object-in-a-sql-server-database – user1619962 Aug 23 '12 at 16:37

2 Answers2

6

There a number of different ways and it depends on how you want to take that object back out again. Without further information, we can't help much.

  1. You can use Entity Framework to map the object to a database table. Each property then would correspond to a table column.
  2. You can serialize the object and store in a single column in a database table - serialize as xml, json, or binary blob.
Leniency
  • 4,984
  • 28
  • 36
4

the proper way it to represent the object as a schema: one or more related tables representing the object and its object graph: properties, subtypes, and referenced types. This lets you query the stowed object as SQL data and use it for other purposes (e.g., reporting).

Alternatively, you can serialize the object instance. You can do it declaratively via the [Serializable] attribute. You can roll your own by implementing the ISerializable interface and serialize it as binary, JSON, some other representation of your choice.

You can serialize to/from XML by using XML serialization attributes or by implementing IXmlSerializable.

Or you can ignore the built-in support for this sort of stuff and serialize it your own way.

Once you've serialized it to a Stream, you can stow that in column of Appropriate Type (varbinary(max) or varchar(max)) depending on how its been serialized.

A third option would be to create a CLR user-defined type and install the assembly in SQL Server. I'm not sure I'd suggest that as a "best practice"

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135