gpt4 book ai didi

C# - 映射器和配置文件

转载 作者:行者123 更新时间:2023-11-30 16:02:37 24 4
gpt4 key购买 nike

我有两个类(class):

public class Customer
{
public string FirstName { get; set; }

public string LastName { get; set; }

public Product Product { get; set; }
}

public class Product
{
public int ProductNumber { get; set; }

public string ProductColor { get; set; }
}


public class Customer_
{
public string FirstName { get; set; }

public string LastName { get; set; }

public Article Article { get; set; }
}

public class Article
{
public int ArticleNumber { get; set; }

public string ArticleColor { get; set; }
}

还有一个实例:

Customer Cus = new Customer()
{
FirstName = "FirstName1",
LastName = "LastName1",
Product = new Product()
{
ProductColor = "ProductColor1",
ProductNumber = 11
}
};

我想从我的实例 Cus 创建一个类 Customer_ 的实例

我使用自动映射器:

MapperConfiguration Config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, Customer_>()
.ForMember(a => a.Article, b => b.MapFrom(c => c.Product));

cfg.CreateMap<Product, Article>()
.ForMember(a => a.ArticleColor, b => b.MapFrom(c => c.ProductColor))
.ForMember(a => a.ArticleNumber, b => b.MapFrom(c => c.ProductNumber));
});

IMapper Mapper = Config.CreateMapper();
var cus_ = Mapper.Map<Customer, Customer_>(Cus);

它可以工作,但我想从配置文件创建 MapperConfiguration。像这样:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Automapper>
<Column source="Product" destination="Article"/>
<Column source="Product.ProductColor" destination="Article.ArticleColor"/>
...
...
...
</Automapper>
</configuration>

这可能吗?

最佳答案

无法使用 AutoMapper 开箱即用地执行此操作,但使用基于类型的 AutoMapper 版本,您当然可以这样做:

cfg.CreateMap(typeof(Customer), typeof(Customer_))
.ForMember("Product").MapFrom("Article");

因此,您只需要遍历 XML,加载类型,并针对每个子节点,为您拥有的两个字符串调用 MapFrom。

您的 XML 看起来不够完整,无法执行此操作,您需要类似以下内容:

<TypeMap SourceType="Customer" DestinationType="Customer_">
<PropertyMap Member="Product" MapFrom="Article">
</TypeMap>

等等

关于C# - 映射器和配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37445588/

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