使用经典的 ado.net 加载相关实体 [英] load related entities using classic ado.net

查看:18
本文介绍了使用经典的 ado.net 加载相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:WPF + MVVM + 存储库模式 + 经典的 ADO.NET + SQL
背景:为简单起见,我们只考虑数据库中的 2 个表,User 和 UserType.

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;}  
}

问题:
使用经典 ado.net(不是 EF 或 LINQ)加载相关实体的最佳方法是什么?我是否必须在 SQL proc 中加入 User 和 UserType 表,然后在代码中填充每个相关实体?但这似乎很乏味,因为相关实体本身可能有几个相关实体,例如类 A -> B -> C -> D 等等

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.

当我们使用EF时,在调试器中我们实际上可以查看当前一级到任何级别的所有相关实体.经典的 ado.net 可以做到吗?

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?

推荐答案

即使在实体框架中,它也不会获取所有相关实体.当您尝试访问它们时会延迟加载实体,从而导致额外的查询,或者您必须专门Include您想要急切获取的实体的路径.

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.

也许您应该为每个类添加一些逻辑,以便它知道如何获取自己的相关模型?这样模型 A 就不必知道模型 B、C 和 D.它可能只需要知道模型 B.而模型 B 知道模型 C 等.

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.

虽然我个人认为这是矫枉过正,如果你只想从两个不同的表中获取数据,你可能应该只使用 SQL JOIN 并使用 SqlDataReader 遍历结果代码>.

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.

这篇关于使用经典的 ado.net 加载相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆