Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF - Mapping generic class to Complex Type

It is possible to map generic class to complex type? I have small class that 3 properties - string, int and generic type, and want to map the string and the int (the string is actually the serialized generic type) to a complex type.

I assume that it isn't possible as the generic class "FQDN" is MyGenericClass<somclass> and the complex type conceptional type is just MyGenericClass Is there clever solution or I'll have to define ComplexType for each usage of the generic class?

like image 902
SimSimY Avatar asked Mar 12 '13 15:03

SimSimY


1 Answers

I don't know if i understood you correctly, but why don't you use a custom cast by overriding the conversion operator. In the following example i casted my generic complex class implicitly to a non-generic class.

Read more @ How do I provide custom cast support for my class?

public class ClassComplex<T> 
{
    public T MyGenericValue { get; set; }
    public string MyStringValue { get; set; }
    public int MyIntValue { get; set; }

    public static implicit operator ClassComplex(ClassComplex<T> a)
    {
        return new ClassComplex() { MyIntValue = a.MyIntValue , MyStringValue = a.MyStringValue };
    }
}

public class ClassComplex
{
    public string MyStringValue { get; set; }
    public int MyIntValue { get; set; }
}

public class Test
{
    public Test()
    {
        ClassComplex<int> ccg = new ClassComplex<int>();
        ccg.MyGenericValue = 1;
        ccg.MyIntValue = 2;
        ccg.MyStringValue = "3";

        ClassComplex cc = ccg;
    }
}
like image 92
gonium Avatar answered Oct 13 '22 01:10

gonium