load related entities using classic ado.net

守給你的承諾、 提交于 2019-12-25 05:29:05

问题


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

Tables

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

Models

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 e.g. 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?


回答1:


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.



来源:https://stackoverflow.com/questions/19282164/load-related-entities-using-classic-ado-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!