Daniel
Daniel

Reputation: 1469

LINQ select with EF Core and cast to derived class without copying properties

I have a LINQ to select records from DB:

List<Companies> enabledCompanies;
using (var ctx = new NavigatorContextExt())
{
    enabledCompanies = ctx.Companies
    .Where(e => e.Enabled)
    .ToList();
}

I have a CompaniesExt class derived from Companies class that contains a few extra properties to be calculated later. I wish to have LINQ return CompaniesExt classes.

I tried the following:

List<CompaniesExt> enabledCompanies;
using (var ctx = new NavigatorContextExt())
{
    enabledCompanies = ctx.Companies
    .Where(e => e.Enabled)
    .Cast<CompaniesExt>()
    .ToList();
}

But I got an InvalidCastException. Is this cast impossible to do? Shall I just use LINQ to select into CompaniesExt and copy all properties by hand?

Upvotes: 1

Views: 505

Answers (1)

jeroenh
jeroenh

Reputation: 26782

The actual runtime type of the entity you get from EF is Company, so no, you can't magically cast that to a derived class.

But it's not required to derive from an entity just to add some properties. Just use the [NotMapped] annotation in your entity itself:

public class Company
{
     public int CompanyID {get;set;}
     // ... other DB properties

     [NotMapped]
     public string SomeProperty { get; set; }
}

If your entities are generated, you can use a partial class to add the unmapped properties:

public partial class Company // other part in generated file
{
     [NotMapped]
     public string SomeProperty { get; set; }
}

Upvotes: 2

Related Questions