Search code examples
c#entity-frameworklambdamappers

Cast an object inside lambda expressions


i'm using EntityTypeConfiguration to map my database.

The problem is, the class T_DOC_GENERIC inherits T_DOC, when I set my relationship WithMany he expects an object T_DOC_GENERIC which he's declared as T_DOC.

public class T_DOC_GENERICMapper : EntityTypeConfiguration<T_DOC_GENERIC>
    {
        T_DOC_GENERICMapper()
        { 
            this.ToTable("T_DOC");
            this.HasKey(tDoc => tDoc.ID);
            this.HasOptional(tDoc => tDoc.T_TYPE)
                .WithMany(tType =>  tType.T_DOC)
                .HasForeignKey(tDoc => tDoc.COD_TYPE);
        }
    }

Cannot implicitly convert type 'System.Collections.Generic.ICollection<Protocol.Models.BaseEntities.T_DOC>' to 'System.Collections.Generic.ICollection<Protocol.Models.BaseEntities.GenericsEntities.T_DOC_GENERIC>'. An explicit conversion exists (are you missing a cast?) D:\PortalProtocolo\Models\Mappers\GenericsMappers\T_DOC_GENERIC.cs

There's a way to cast inside the lambda expression?

I tried an explicit cast like .WithMany((T_DOC)tType => tType.T_DOC) but I have no ideia how!

Someone can help me?


Solution

  • Write a converter to convert/map from T_DOC to T_DOC_GENERIC (return type) in the T_DOC class to perform this cast:

    public T_DOC_GENERIC ConvertToGeneric(T_DOC source)
    {
        T_DOC_GENERIC destination = new T_DOC_GENERIC(){};
    
        /* Map T_DOC source to T_DOC_GENERIC destination here */
    
        return T_DOC_GENERIC;
    }
    

    You can add this to an existing class or make it static if you prefer.