0

我有工作解决方案,但有点怀疑我是否正确。我有从中派生 3 个其他类 Ad 的基类:

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

我的地址类如下所示:

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; }
}

现在我正在使用带有此映射的自动映射器:

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();
        });

AutoViewModel 看起来像这样:

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; }
}

在我的创建和编辑操作中,我使用了这个绑定:

 [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);
    }

这种方式正确吗?有优雅的方法吗?我必须明确指定 AddressId,否则我会收到重复的外键错误消息...

4

0 回答 0