locked
Finding inherited object by ID - Entity Framework RRS feed

  • Question

  • As you can see in the following image, I have a model with a base class "Person" and both entities "Kunde" and "Techniker" inherit the base class.

    abload.de/img/snapshot_entitydbmodefvkge.png  (cannot post pictures due to not being verified)

    Now I've got following problem. When I try to use the method Find to get an object of the derived class Kunde with given ID, it tells me that OfType<TResult> is a method and isn't valid in this context. I've added a screenshot just in case my description of the problem isn't perfectly understandable.

    abload.de/img/snapshot_kundegetbyid29rtp.png

    public Kunde GetById(int id)
    {
       return dbModel.PersonMenge.OfType<Kunde>.Find(id);
    }

    I've also tried to drop the OfType<Kunde> but it obviously tells me that the object Person cannot be implicitly converted to Kunde.

    Is there anything I'm missidng here?



    • Edited by Hans Wurs Saturday, November 24, 2012 7:40 PM missing code
    Saturday, November 24, 2012 7:37 PM

Answers

  • OfType<T> is an extension method so you need to call OfType<Kunde>(). But you won't be able to use Find() as that is a method on the DbSet. I think the two best options would be:

    return dbModel.PersonMenge.OfType<Kunde>().FirstOrDefault(p => p.Id == id);

    Or

    return dbModel.PersonMenge.Find(id) as Kunde;

    Hope it helps.
    • Marked as answer by Hans Wurs Sunday, November 25, 2012 11:06 AM
    Sunday, November 25, 2012 3:12 AM