简体   繁体   中英

load related entities using classic ado.net

Environment: WPF + MVVM + Repository Pattern + classic ADO.NET + SQL
Background: For simplicity let's consider only 2 tables in database, User and UserType.

<i>User</i> : Id, Username, TypeId(fk ref UserType.Id)  
<i>UserType</i> : Id (pk), TypeName  

public class User {  
public int Id {get;set;}  
public string Username {get;set;}    
public UserType Type {get;set;}  
}  

public class UserType {  
public int Id {get;set;}  
public string TypeName {get;set;}  
}

Questions:
What is best way to load related entities using classic ado.net (not EF or LINQ)? Do I have to join User and UserType tables in SQL proc and then in code populate each related entity? But that seems tedious as related entity itself may have couple of related entities eg class A -> B -> C -> D etc.

When we use EF, in debugger we can actually view all the related entities of current one to any no of levels. Is that possible with classic ado.net?

Even in Entity Framework it doesn't fetch all related entities. Either it lazy loads entities when you try to access them which results in additional queries, or you have to specifically Include the paths for entities that you want to eagerly fetch.

Maybe you should add some logic for each class so that it knows how to fetch its own related models? This way Model A doesn't have to know about models B, C, and D. It may only need to know about Model B. While Model B knows about Model C, etc.

You'd just have to compartmentalize your code so that each entity knows how to fetch the models which are directly related to it.

Though personally I think this is overkill, if you only want to fetch data from two different tables you should probably just use a SQL JOIN and loop through the results with a SqlDataReader .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM