AutoMapper устанавливает нулевой объект назначения - PullRequest
1 голос
/ 22 марта 2019

Я следил за этой статьей: https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f

Но когда я доберусь до фактической части картирования, мой пункт назначения будет нулевым. Может кто-нибудь сказать мне, что я делаю не так?

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<AppDbContext>(
            options => options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddScoped<ICreditCardApplicationRepository,
                           EntityFrameworkCreditCardApplicationRepository>();

        services.AddAutoMapper();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

CreditCardApplicationProfile

public class CreditCardApplicationProfile : Profile
{
    public CreditCardApplicationProfile()
    {
        CreateMap<NewCreditCardApplicationDetails, CreditCardApplication>();
    }   
}

Полный ApplyController.cs, но меня интересует метод индекса HttpPost.

public class ApplyController : Controller
{
    private readonly ICreditCardApplicationRepository _applicationRepository;
    private readonly IMapper _mapper;


    public ApplyController(
        ICreditCardApplicationRepository applicationRepository,
        IMapper mapper
    )
    {
        _applicationRepository = applicationRepository;
        _mapper = mapper;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(NewCreditCardApplicationDetails applicationDetails)
    {
        if (!ModelState.IsValid)
        {
            return View(applicationDetails);
        }

        CreditCardApplication cca = _mapper.Map<CreditCardApplication>(applicationDetails);

        await _applicationRepository.AddAsync(cca);

        return View("ApplicationComplete", cca);
    }

    public IActionResult Error()
    {
        return View();
    }
}

У меня изначально была только строка CreditCardApplication cca = _mapper.Map (applicationDetails);

но комментатор жаловался:

The type arguments for method 'IMapper.Map<TDestination>(object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.  

Это привело к тому, что я попытался указать тип, и теперь он возвращает ноль. Может кто-нибудь сказать мне, что я делаю не так, пожалуйста?

Добавление определений классов ниже:

public class CreditCardApplication
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public decimal GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}



public class NewCreditCardApplicationDetails
{
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Please provide a first name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Please provide a last name")]
    public string LastName{ get; set; }

    [Display(Name = "Age (in years)")]
    [Required(ErrorMessage = "Please provide an age in years")]
    [Range(18,int.MaxValue, ErrorMessage = "You must be at least 18 years old")]
    public int? Age { get; set; }

    [Display(Name = "Gross Income")]
    [Required(ErrorMessage = "Please provide your gross income")]        
    public decimal? GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...