2

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.


        }
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

2 Answers2

2

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();
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103
  • Please read http://stackoverflow.com/questions/11686727/adding-reference-to-entity-causing-exception for further details. – LCJ Jul 27 '12 at 13:58
1

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.

Martin1921
  • 653
  • 1
  • 9
  • 12