How does .Include() Work?

2019-08-06 10:43发布

问题:

Hi I created a database using an Entities diagram in visual studio where i added navigation properties. I created it using this tutorial http://geekswithblogs.net/danemorgridge/archive/2009/10/29/using-visual-studio-2010-beta-2-to-do-entity-framework.aspx It looks like this

User Table
IdUser    Name    IdAccount
1         Ron      2
2         Carl     1

Navigation property: Account (one to one relation)

Account table
IdAccount    Amount
1             50
2             30

Navigation property: Account (one to one relation Notice that user1 has account 2 and user2 has account 1

I do a: var user = infoDB.Users.Include("Account");

This displays:
Ron $50
Carl $30

It shows that Ron has $50 which is the amount of account1, which is wrong because Ron has account number 2....

Why isn't this working?

I have come across with this in several tables I have, not necessarily the idUser has to be the IdAccount, this is just an example to illustrate the problem..

Any ideas? I have still been working on this I did the database from scratch and IdAccount IS the foreign key of Account table, but it is doing the same thing...

I'm doing this in an ASP mvc framework it's like the query from the music tutorial, but there it seems to be working fine with Genres.Include("Albums") does it have to do with the fact that it's a one-to-one relationship?

回答1:

I would suspect that you generated the EDMX from the database when the foreign key was wrong and then updated the database so that it was correct.

If you check the properties of the Navigation Property it should break down to field/FK level and you'll be able to see this.

If you delete the edmx and recreate from database it should work as expected.

We can confirm this by looking at the edmx xml as well.



回答2:

I followed this from your other question and I think it is an incorrect foreign key relationship issue. My guess is that it is because your foreign key on user is called Id, where as EF expects Id to be the primary key. Typically the foreign key on on User would be User.AccountId instead of User.Id.



回答3:

From here

Code First will now infer that any property named <navigation property name><primary key property name> (i.e. SubjectISBN), <principal class name><primary key property name> (i.e. BookISBN) or <primary key property name> (i.e. ISBN), with the same data type as the primary key, represents a foreign key for the relationship. If multiple matches are found then precedence is given in the order listed above. Foreign key detection will not be case sensitive.

Try turning your key names around "AccountId" instead of "IdAccount". My guess is that it's using IdUser as a foreign key for the User<->Account relationship.