1

I've read this answer The entity cannot be constructed in a LINQ to Entities query but still, feel confused.

var ProductAndBuildInfoList= (
    from p in db.Product
    join pbc in db.product_builds_children on p.BuildId equals pbc.BUILD_ID
    select new ProductAndBuildInfo {
        Id = p.Id,
        Name = p.name,
        BuildRequestId = pbc.BUILD_REQ_ID
    }
).ToList();

When I executed the above query, it threw out the exception

"The entity cannot be constructed in a LINQ to Entities query"

Here is the class for both ProductAndBuildInfo and Product

public class ProductAndBuildInfo : Product {
    public long BuildRequestId { get; set; }
}

public class Product {
    public long Id { get; set; }
    public string Name { get; set; }
}

I understand that we can't construct an object if it's a mapped entity, then what's the correct way to construct a new object inherited from a mapped entity? Copy all fields from the upper class to the lower class seems an unclean way to me.

rj487
  • 4,476
  • 6
  • 47
  • 88
  • 1
    The solution should be the same as with non-inherited one. Either create a DTO or map to anonymous type and after fetching from db remap to your class. – Guru Stron Apr 16 '21 at 22:08
  • Doesn't ProductAndBuildInfo consider as a `DTO`? it only contains property. @GuruStron – rj487 Apr 16 '21 at 22:22
  • It seems that because it is inherited from entity - no. – Guru Stron Apr 16 '21 at 22:31
  • Then, if I need a new DTO which wants all field from class `Product`, what is the best way to do? – rj487 Apr 18 '21 at 19:37
  • You always can move shared fields from entity to some base class and then inherit both entity and DTO from it. – Guru Stron Apr 18 '21 at 20:43
  • @GuruStron so, you are saying I should create a class call baseProduct and contains all field, then an entity (Product) and DTO(ProductAndBuildInfo) both inherit from the baseProduct? Would you like to give an example? This question need an accept answer. – rj487 Apr 19 '21 at 01:27
  • Hey, it's working, thanks. Would you like to answer it? @GuruStron – rj487 Apr 19 '21 at 17:02

1 Answers1

0

Move your shared fields to some new class:

public class ProductBase {
    public long Id { get; set; }
    public string Name { get; set; }
}

And then inherit both entity and DTO from it:

public class Product : ProductBase {
}

public class ProductAndBuildInfo : ProductBase {
    public long BuildRequestId { get; set; }
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132