How to declare (map) a SQL_VARIANT in a Model - C # [UWP]

0

Good thing I have a table in SQL:

CREATE TABLE Parametros(
    Empid       int NOT NULL CONSTRAINT [FK_Parametros_Empid] REFERENCES Empresa(id),
    Codigo      varchar(25) NOT NULL,
    Valor       sql_variant NULL,
    CONSTRAINT [PK_Parametros] PRIMARY KEY (Empid,Codigo))

And then I have to create the model of that table to work with, and I do not know how to declare the column 'value' in the model.

Thanks

    
asked by Wilmilcard 17.10.2018 в 14:55
source

2 answers

0

I found the solution, in the model I had to add [Column(TypeName = "sql_variant")] to the SQL_Variant field in the Database to be able to map it, in my case the column is called Valor

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public partial class Parametro : Entidad
{
    public override string ToString() { return Codigo; }

    [Key]
    public int Empid { get; set; }

    public string Codigo { get; set; }

    [Column(TypeName = "sql_variant")]
    public object Valor { get; set; }
}
    
answered by 22.10.2018 / 15:12
source
0

I do not recommend using this type of data, at least if you are going to use it in applications because it is clear that you will not know what type of data persists

But you will have to return together with the value of what type of data persisted, for that use SQL_VARIANT_PROPERTY

sql_variant (Transact-SQL)

As you will see back

SELECT Empid, 
       Codigo,
       Valor, 
       SQL_VARIANT_PROPERTY(Valor,'BaseType') AS 'DataType'
FROM Parametros

to have the type of data you will have to apply logic to know what specific type to cast in .net Having the type of data one could see of making a generic converter

Convert or TryParse from string to T (generic) possible? work around?

public static T TryParse<T>(string inValue)
{
    TypeConverter converter =
        TypeDescriptor.GetConverter(typeof(T));

    return (T)converter.ConvertFromString(null,
        CultureInfo.InvariantCulture, inValue);
}

but you have to see how it is that you intend to use the data in the application, maybe use a string for all types of data to be simpler

    
answered by 17.10.2018 в 16:08