【发布时间】:2019-01-13 01:32:30
【问题描述】:
我正在使用 ADO.NET 将一堆数据从数据库读取到内存对象中。
这是我的领域模型:
// Question.cs
public class Question
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<Tag> Tags { get; set; }
}
// Tag.cs
public class Tag
{
public int ID { get; set; }
public string Name { get; set; }
}
在检索问题列表时,我想获取每个问题的相关标签。我可以这样做:
// QuestionRepository.cs
public IList<Question> FindAll()
{
var questions = new List<Question>();
using (SqlConnection conn = DB.GetSqlConnection())
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from questions";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Question question = new Question();
// Populate the question object using reader
question.Load(reader);
questions.Add(question);
}
reader.Close();
}
}
return questions;
}
// Question.cs
public void Load(SqlDataReader reader)
{
ID = int.Parse(reader["ID"].ToString());
Title = reader["Title"].ToString();
Description = reader["Description"].ToString();
// Use Tag Repository to find all the tags for a particular question
Tags = tagRepository.GetAllTagsForQuestionById(ID);
}
return questions;
}
// TagRepository.cs
public List<Tag> GetAllTagsForQuestionById(int id)
{
List<Tag> tags = new List<Tag> ();
// Build sql query to retrive the tags
// Build the in-memory list of tags
return tags;
}
我的问题是,是否有从数据库中获取相关对象的最佳实践/模式?
我在加载相关数据时遇到的大多数 SO 问题都提供了实体框架的解决方案。这个duplicate question.没有答案
即使我的代码有效,我也想知道其他方法可以做到这一点。我遇到的针对我的特定问题的最接近的解释是 Martin Fowler 的 Lazy Load 模式,我相信这将导致以下实现:
public class Question
{
private TagRepository tagRepo = new TagRepository();
private IList<Tag> tags;
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<Tag> Tags {
get
{
if (tags == null)
{
tags = tagRepo.GetAllTagsForQuestionById(ID);
}
return tags;
}
}
}
还有其他选择吗?
【问题讨论】:
-
没有理由手动执行此操作。我从不推荐使用 Dapper(因为它可以优雅地处理像
DBNull这样的事情)。 -
您可以使用任何 ORM(EF、Dapper、NHibernate 等)...它们为您简化了 DB 访问...延迟加载可以简单地在 EF 中打开/关闭,这不应该让您担心...如果您不想使用任何这些 ORM(我不确定您为什么要这样做?)您可以使用 ADO.NET Entity Framework 使用原始 sql。另请注意,您在这里寻求推荐......这是一个离题主题
标签: c# orm ado.net lazy-loading domain-model