Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Convert DataRow to Object with AutoMapper

I can successfully map from IDataReader to a List of objects but when I want to take one DataRow it doesn't seem to work as expected.

Am I missing something simple here?

[TestFixture]
public class AutomapperTest
{
    [Test]
    public void TestMethod1()
    {
        DataTable dt = new DataTable("contact");
        dt.Columns.Add("FirstName");
        dt.Columns.Add("LastName");
        dt.Columns.Add("Line1");
        dt.Columns.Add("Line2");
        dt.Columns.Add("Line3");
        dt.Columns.Add("Suburb");
        dt.Columns.Add("State");
        dt.Columns.Add("Postcode");

        DataRow row = dt.NewRow();
        row.ItemArray = new [] { "Little", "Johnny", 
                                 "1 Random Place", "", "", 
                                 "Windsor", "Qld", "4030" };

        var dest = Mapper.DynamicMap<myObject>(row);

        Assert.AreEqual(row["FirstName"], "Little");
        Assert.IsNotNull(dest);
        Assert.AreEqual(dest.FirstName, "Little");
    }
}

Destination type:

public class myObject
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string Line3 { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
    public string Postcode { get; set; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to implement your own custom value resolver

https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers

UPDATE

public class CustomResolver : IValueResolver
{
    public ResolutionResult Resolve(ResolutionResult source)
    {
        return source.New( Convert.ChangeType((source.Context.SourceValue as DataRow)[source.Context.MemberName], source.Context.DestinationType));
    }
}

and here is how to use it

Mapper.CreateMap<DataRow,myObject>().ForAllMembers(m=>m.ResolveUsing<CustomResolver>());
var dest = Mapper.Map<myObject>(row);

I recommend using Dapper. That way your data coming from database will be strongly typed or dynamic, and Automapper should be able to figure out the mappings.

CSV files can be read by Dapper through ODBC, I believe. But for CSV I'd recommend the LinqToCSV Nuget package instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...