Я могу сохранить 'Объект' в базе данных SQL Server?

"ABABAB".replace(/B/g, "A");

Как всегда: не используйте regex, если Вы не имеете к. Для замены простой строки идиома:

'ABABAB'.split('B').join('A')

Затем Вы не должны волноваться о проблемах заключения в кавычки, упомянутых в ответе Gracenotes.

45
задан marc_s 19 August 2009 в 12:04
поделиться

4 ответа

Вы можете использовать VARBINARY (MAX) в SQL Server, если хотите. Вы можете хранить там объекты любого типа размером до 2 ГБ.

Для доступа к ним вы можете использовать ADO.NET - примерно так:

object yourMysteryObject = (whatever you like it to be);

MemoryStream memStream = new MemoryStream();
StreamWriter sw = new StreamWriter(memStream);

sw.Write(yourMysteryObject);

SqlCommand sqlCmd = new SqlCommand("INSERT INTO TableName(VarBinaryColumn) VALUES (@VarBinary)", sqlConnection);

sqlCmd.Parameters.Add("@VarBinary", SqlDbType.VarBinary, Int32.MaxValue);

sqlCmd.Parameters["@VarBinary"].Value = memStream.GetBuffer();

sqlCmd.ExecuteNonQuery();

Marc

30
ответ дан 26 November 2019 в 21:18
поделиться

I would use JSON to convert the object to a string, and store it in a VARCHAR or TEXT field. Not only the data is stored in a human-readable format, but it's also also readable from different languages, since pretty much every mainstream language has a JSON parser available.

The link I posted has links to several libraries in many languages (including C#), I have used this one a couple times in the past.

24
ответ дан 26 November 2019 в 21:18
поделиться

As others have said, serialization may be the key here (assuming you don't want to use ORM to store the properties as columns in a table, which seems much more direct).

Some caveats though; a database is:

  • long term storage
  • not related to your .NET code

As such, you do not want to use any serialization technique that is platform-specific or version-specific. You will often see people mention BinaryFormatter for persistance, but this falls into both of the above traps. You would be scuppered if you ever changed platform, or even if you just change some properties.

You need an implementation-independent approach; the simplest (which also retains the ability to be human readable) is xml or json, perhaps via XmlSerializer or Json.NET (stored in a [n]varchar(max)). If you don't care about human readable, "protocol buffers" (fast/binary) would do well (stored in a varbinary(max)), and is available for most platforms (including C#/.NET/etc).

12
ответ дан 26 November 2019 в 21:18
поделиться

Для этого вам нужно сериализовать ваш объект. Вы можете посмотреть здесь примеры:

http://www.c-sharpcorner.com/UploadFile/bipinjoshi/serializingObjectsinCS11102005234746PM/serializingObjectsinCS.aspx

1
ответ дан 26 November 2019 в 21:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: