LCJ
LCJ

Reputation: 22661

EF Model First : Subclass object does not appear in Context

I have a model created using Model First approach. When I try to access the Book entity using the context it is not listed there; but the selling item is listed. What change need to be done inorder to add the Book entity to the context?

Note: Please read Adding reference to entity causing Exception and Entity Framework: Get Subclass objects in Repository for further details.

enter image description here

Model

enter image description here

Code

enter image description here

    static void Main(string[] args)
    {
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new MyModelFirstTestContainer(connectionstring))
        {
            Book book = new Book();
            book.AvailabilityStatus = "Available";
            book.Price = 100;
            book.Title = "World visit";

           //db.


        }

Upvotes: 2

Views: 221

Answers (2)

Wouter de Kort
Wouter de Kort

Reputation: 39898

The Entity Framework does not create separate ObjectSets for inherited items on your Context.

Instead you can use the OfType<T>() method like this:

from b in db.SellingItems.OfType<Book>()
where b.Title = "my title"
select b;

Here is the MSDN Documentation for OfType

If you want to add an inherited entity you will use the parent ObjectSet.

Book b = ...;
db.SellingItems.Add(b);
db.SaveChanges();

Upvotes: 2

Martin1921
Martin1921

Reputation: 653

I don't know how you could add them there, but would you really want that anyway?

Instead I'd use "db.SellingItems.OfType()". This way you'd request all books and get them casted already. If you call db.SellingItems, then you get all SellingItems with the proper instances.

Upvotes: 1

Related Questions