Ado.Net Entity: Object does not display related members (foreign keys)

I have a simple database: User, Account. The user has a one-to-many relationship with the account.

I created an ado.net entity data model and I can create users and accounts and even link them together. In the database, account.user_id is correctly populated, so theoretically I should be able to use User.Account.ToList () in C # through the entity.

However, when I try to access User.Account.ToList (), I get null results.

User user = db.User.First(U => U.id == 1);
List<Account> accounts = user.Account.ToList(); ##count = 0...

When I add the following code before the previous code, it unexpectedly returns me the correct counter.

 Account account1 = db.Account.First(A => A.id == 1);
 Account account2 = db.Account.First(A => A.id == 2);
 User user = db.User.First(U => U.id == 1);
 List<Account> accounts = user.Account.ToList(); ##count = 2...??

What am I missing here?

+3
3

ObjectQuery.Include. , .

User user = db.User.Include("Account").First(u => u.id == 1);

"Account". - MyEntities. , .

+2

, Entity - , , . /, , , :

.

    if(!user.Account.IsLoaded)
        user.Account.Load();

:

public static class EntityExtensions
{
    public static void EnsureLoaded(this RelatedEnd relatedEnd)
    {
        if (!relatedEnd.IsLoaded)
            relatedEnd.Load();
    }
}

:

user.Account.EnsureLoaded();

End, , - ,

account.UserReference.EnsureLoaded();

rwwilden, , Include, .

+2

, .:)

.

user.Account.Load();

.

+1
source

Source: https://habr.com/ru/post/1706378/


All Articles