Cast IEnumerable<Inherited> To IEnumerable<Base>

Posted by david2342 on Stack Overflow See other posts from Stack Overflow or by david2342
Published on 2013-11-01T20:19:05Z Indexed on 2013/11/01 21:53 UTC
Read the original article Hit count: 203

Filed under:
|
|
|

I'm trying to cast an IEnumerable of an inherited type to IEnumerable of base class.

Have tried following:

var test = resultFromDb.Cast<BookedResource>();

return test.ToList();

But getting error:

You cannot convert these types. Linq to Entities only supports conversion primitive EDM-types.

The classes involved look like this:

public partial class HistoryBookedResource : BookedResource
{
}

public partial class HistoryBookedResource
{
    public int ResourceId { get; set; }
    public string DateFrom { get; set; }
    public string TimeFrom { get; set; }
    public string TimeTo { get; set; }
}

public partial class BookedResource
{
    public int ResourceId { get; set; }
    public string DateFrom { get; set; }
    public string TimeFrom { get; set; }
    public string TimeTo { get; set; }
}

[MetadataType(typeof(BookedResourceMetaData))]
public partial class BookedResource
{
}

public class BookedResourceMetaData
{
    [Required(ErrorMessage = "Resource id is Required")]
    [Range(0, int.MaxValue, ErrorMessage = "Resource id is must be an number")]
    public object ResourceId { get; set; }

    [Required(ErrorMessage = "Date is Required")]
    public object DateFrom { get; set; }

    [Required(ErrorMessage = "Time From is Required")]
    public object TimeFrom { get; set; }

    [Required(ErrorMessage = "Time to is Required")]
    public object TimeTo { get; set; }
}

The problem I'm trying to solve is to get records from table HistoryBookedResource and have the result in an IEnumerable<BookedResource> using Entity Framework and LINQ.

UPDATE:

When using the following the cast seams to work but when trying to loop with a foreach the data is lost.

resultFromDb.ToList() as IEnumerable<BookedResource>;

UPDATE 2:

Im using entity frameworks generated model, model (edmx) is created from database, edmx include classes that reprecent the database tables.

In database i have a history table for old BookedResource and it can happen that the user want to look at these and to get the old data from the database entity framework uses classes with the same name as the tables to receive data from db. So i receive the data from table HistoryBookedResource in HistoryBookedResource class.

Because entity framework generate the partial classes with the properties i dont know if i can make them virtual and override.

Any suggestions will be greatly appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ