gpt4 book ai didi

c# - 为什么Automapper会自动将Driver.Name映射到DriverName

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

我有以下类(class):

public partial class ScheduledDeduction
{
public int ID { get; set; }

public int DriverId { get; set; }

public string Description { get; set; }

public DateTime DateTime { get; set; }

public decimal Amount { get; set; }

public virtual Driver Driver { get; set; }
}

public partial class Driver
{

public int ID { get; set; }

public int CompanyId { get; set; }

public string Name { get; set; }

和 View 模型类:

public abstract class ScheduledDeductionDetailVM
{
public int ID { get; set; }

[Display(Name = "Driver Name")]
public string DriverName { get; set; }

public string Description { get; set; }

[Display(Name = "Date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public System.DateTime DateTime { get; set; }

[Display(Name = "Amount")]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal Amount { get; set; }
}

我有以下 Automapper 规则:

CreateMap<Infrastructure.Asset.ScheduledDeduction, ViewModels.ScheduledDeductionDetailVM>();

并尝试使用:

ScheduledDeduction scheduledDeduction = db.ScheduledDeductions.Find(id);
ScheduledDeductionDetailVM model = mapper.Map<ScheduledDeductionDetailVM>(scheduledDeduction);

而且有效!为什么? ScheduledDeductionDetailVM 有属性 DriverName ,它可以从 ScheduledDeduction.Driver.Name 获得,它根本没有描述。但它映射正确...

最佳答案

这是框架的一个特性。

根据 documentation about Flattening

One of the common usages of object-object mapping is to take a complex object model and flatten it to a simpler model.

....

When you configure a source/destination type pair in AutoMapper, the configurator attempts to match properties and methods on the source type to properties on the destination type. If for any property on the destination type a property, method, or a method prefixed with "Get" does not exist on the source type, AutoMapper splits the destination member name into individual words (by PascalCase conventions).

关于c# - 为什么Automapper会自动将Driver.Name映射到DriverName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44485567/

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