Independent Association does not retrieve all rows when no foreign key constraint exists in database

93 Views Asked by At

I am using EF6.1 Database First/ObjectContext/POCOs.

I have a table called Foo and another table called FooHistory. This is how my model looks like:

enter image description here

Due to legacy reasons, FooNo is primary key on Foo, but not on FooHistory and a foreign key constraint does not exist in the database. However, this is a logical foreign key, so I set up a 1 to Many independent association between Foo and FooHistory. The Principal/Dependent property is FooNo.

The following Linq-to-Entities query:

        var qry = from f in context.Foo.Include("History")
                  where f.FooNo.Trim() == "SomeNo"
                  select f.History.Count();

returns a value of 6, whereas the SQL sent to the database returns 10 rows (which is what I want).

I managed to get the query to give me the full 10 rows by creating a foreign key constraint in the database on FooNo and updating the model. At that point EF the Referential Constraint in the association's properties changed to the name of the database constraint. The multiplicity also changed, becoming 0...1 to Many.

However, I'd like to understand why the first approach does not work - Why are the results different when in both cases the query sent to the database is the same? Exactly what is going on internally?

0

There are 0 best solutions below