gpt4 book ai didi

c# - 是否可以使用自动映射器将 IDataReader 映射到嵌套的 DTO?

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:14 25 4
gpt4 key购买 nike

我希望我可以将平面数据读取器映射到嵌套的 DTO。运行以下代码,名称为空。我做错了什么还是这不可能?

class Program
{
public class Person
{
public int id { get; set; }
public Name name { get; set; }
}

public class Name
{
public string first_name { get; set; }
public string last_name { get; set; }
}

static void Main(string[] args)
{
DataTable table = CreateSampleDataTable();
Mapper.CreateMap<IDataReader, Person>();
Mapper.CreateMap<IDataReader, Name>();

var results = Mapper.Map<IDataReader, IList<Person>>(table.CreateDataReader());
}

private static DataTable CreateSampleDataTable()
{
var table = new DataTable();

table.Columns.Add("id", typeof(int));
table.Columns.Add("first_name", typeof(string));
table.Columns.Add("last_name", typeof(string));

table.Rows.Add(100, "Jeff", "Barnes");
table.Rows.Add(101, "George", "Costanza");
table.Rows.Add(102, "Stewie", "Griffin");
table.Rows.Add(103, "Stan", "Marsh");
table.Rows.Add(104, "Eric", "Cartman");
return table;
}
}

最佳答案

可能与 ValueInjecter :

public class DanRyan
{
[Test]
public void Main()
{
var persons = new List<Person>();
var table = CreateSampleDataTable();
var reader = table.CreateDataReader();

while (reader.Read())
{
var p = new Person();

p.InjectFrom<ReaderInjection>(reader);

p.name = new Name();
p.name.InjectFrom<ReaderInjection>(reader);

persons.Add(p);
}

persons.Count.IsEqualTo(5);
persons[0].id.IsEqualTo(100);
persons[0].name.first_name.IsEqualTo("Jeff");
persons[0].name.last_name.IsEqualTo("Barnes");
}

public class Person
{
public int id { get; set; }
public Name name { get; set; }
}

public class Name
{
public string first_name { get; set; }
public string last_name { get; set; }
}

private static DataTable CreateSampleDataTable()
{
var table = new DataTable();

table.Columns.Add("id", typeof(int));
table.Columns.Add("first_name", typeof(string));
table.Columns.Add("last_name", typeof(string));

table.Rows.Add(100, "Jeff", "Barnes");
table.Rows.Add(101, "George", "Costanza");
table.Rows.Add(102, "Stewie", "Griffin");
table.Rows.Add(103, "Stan", "Marsh");
table.Rows.Add(104, "Eric", "Cartman");
return table;
}

public class ReaderInjection : KnownSourceValueInjection<IDataReader>
{
protected override void Inject(IDataReader source, object target)
{
for (var i = 0; i < source.FieldCount; i++)
{
var activeTarget = target.GetProps().GetByName(source.GetName(i), true);
if (activeTarget == null) continue;

var value = source.GetValue(i);
if (value == DBNull.Value) continue;

activeTarget.SetValue(target, value);
}
}
}
}

关于c# - 是否可以使用自动映射器将 IDataReader 映射到嵌套的 DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3577046/

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