gpt4 book ai didi

c# - 将sql查询结果映射到领域模型

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:15 24 4
gpt4 key购买 nike

我有以下领域模型:

public class Company
{
public int Id { get; private set; }
public string Name { get; private set; }
public BlaBla BlaBla { get; private set; }
...
...

public void ChangeName(string newName)
{
//business logic here

Name = newName;
}
}

我们已经使用 Entity Framework 实现了存储库模式,并且运行良好。对于一个非常具体的案例(使用遗留数据库),我们需要跳过 EF 并使用普通的 sql 查询并自己进行映射。

映射的代码(伪代码)如下:

using connection
using command
company = new Company();
while (reader.read())
company.ChangeName(reader["company_name"]);
end while
end using
end using

正如你所看到的,Company 的所有属性都是“私有(private)集”,因为我们正在实践领域驱动设计,所以我们不能写 company.Id = reader["Id"] ,我们必须使用领域方法来“填充”Company 对象的属性。

是否有像 EF 那样优雅的方式来做到这一点?如何在不创建方法 SetId(int id) 的情况下设置 Id 属性?

最佳答案

您可以使用 PropertyInfo(如下所示):

foreach (PropertyInfo propInfo in theType.GetProperties())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Trim().ToLower() == propInfo.Name.Trim().ToLower())
{
object asObj = reader.GetValue(i);
if (asObj is System.DBNull) propInfo.SetValue(thisRow, null, null);
else propInfo.SetValue(thisRow, reader.GetValue(i), null);
}
}
}

类型将是您要将属性映射到的 typeof(YourType)

关于c# - 将sql查询结果映射到领域模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com