0

I have working solution, but a bit doubt if I made it correctly. I have base class from which derive 3 other classes Ad:

public class Ad
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Address Address { get; set; }
}

My Address class look like this:

public class Address
{
    [ForeignKey("Ad")]
    public int AddressId { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public virtual Ad Ad { get; set; }
}

Now I'm using automapper with this mapping:

Mapper.Initialize(config => 
        {
            config.CreateMap<Auto, AutoViewModel>()
                            .ForMember(m => m.City, vm => vm.MapFrom(m => m.Address.City))
                            .ForMember(m => m.Street, vm => vm.MapFrom(m => m.Address.Street))
                            .ForMember(m => m.ZipCode, vm => vm.MapFrom(m => m.Address.ZipCode)).ReverseMap();
        });

Where AutoViewModel looks like this:

public class AutoViewModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Street { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
}

In my Create and Edit actions I use this binding:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, AutoViewModel vm)
    {
        Address address = new Address();
        address.AddressId = vm.Id;
        address.City = vm.City;
        address.Street = vm.Street;
        address.ZipCode = vm.ZipCode;

        var auto = Mapper.Map<Auto>(vm);

        auto.Address = address;

        if (id != auto.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(auto);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AutoExists(auto.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(auto);
    }

Is this way correct? Is there elegant way to do it? I had to specify AddressId explicit because otherwise I'm getting duplicate Foreign key error message...

Almat P
  • 1
  • 1

0 Answers0