C#: How would you store arbitrary objects in an SQL Server?

前端 未结 3 1862
挽巷
挽巷 2021-01-06 19:05

Lets say you have various objects of arbitrary type that you would like to store in a key+value type of table. Key could for example be an int, string or guid. What would th

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 19:41

    Usually I use a specific column for a certain kind of value.

    Eg.

    • Guid: UNIQUEIDENTIFIER
    • numbers like int, decimal, byte etc: DECIMAL
    • string: NVARCHAR
    • DateTime: DATETIME

    I'm using NHibernate, there it is very easy to have a subclass for each specific type and map them to the same table, each using a specific field for its specific value. I get a table like this:

    create table dbo.Value (
      Name NVARCHAR(80) not null,
      Type NVARCHAR(6) not null,
      TextValue NVARCHAR(500) null,
      GuidValue UNIQUEIDENTIFIER null,
      NumericValue DECIMAL(36, 18) null,
      DateTimeValue DATETIME null
    )
    

    The column Type is either 'TEXT', 'GUID', 'NUMBER' or 'DATE'. This is all done by NHibernate, but can easily be used and manipulated without it.

    Additionally you could store a reference to another entity by using an NH any type as value (storing a primary key and an entity name).

提交回复
热议问题