如何与 ICollection EF 一起更新记录

问题描述 投票:0回答:1

如果没有

ICollection
,我可以更新数据,但我尝试更新
ICollection
记录失败。

我尝试了此处显示的代码,但出现错误

一个或多个外键属性不可为空

我需要更新子记录,如果记录不存在,我需要插入它们。或者我们也可以删除然后插入。请帮忙 - 我做错了什么?

FHASMstBank
是实体:

public partial class FHASMstBank
{
    public FHASMstBank()
    {
        this.FHASMstBankDomains = new HashSet<FHASMstBankDomain>();
        this.FHASMstBankProducts = new HashSet<FHASMstBankProducts>();
    }

    [Key]
    public short BankId { get; set; }
    public string BankName { get; set; }
    public string BankCode { get; set; }
    public string BankDescription { get; set; }
    public bool IsActive { get; set; }

    public virtual ICollection<FHASMstBankDomain> FHASMstBankDomains { get; set; }
    public virtual ICollection<FHASMstBankProducts> FHASMstBankProducts { get; set; }
}

这是我的

UpdateBank
方法。我将参数作为带有更新值的银行传递:

 public CreateBankResponse UpdateBank(Bank bank)
 {
     try
     {
         var mapper = _mapper.Map<FHASMstBank>(bank);
         var entity = _context.Set<FHASMstBank>().Local.FirstOrDefault(entry => entry.intBankID.Equals(bank.intBankID));

         entity.txtBankName = bank.txtBankName;
         entity.txtBankCode = bank.txtBankCode;
         entity.txtBankDescription = bank.txtBankDescription;
         entity.flgIsActive = bank.flgIsActive;
         entity.dtValidFrom = bank.dtValidFrom;
         entity.txtCreatedBy = bank.txtCreatedBy;
         entity.dtCreatedOn = bank.dtCreatedOn;
         entity.txtModifiedBy = bank.txtModifiedBy;
         entity.dtModifiedOn = bank.dtModifiedOn;
         entity.txtBankGroup = bank.txtBankGroup;
         entity.FHASMstBankDomains = bank.FHASMstBankDomains; //Icollection records
         entity.FHASMstBankProducts  = bank.FHASMstBankProducts;//Icollection records

         if (entity != null) // I'm using an extension method
         {
             // detach
             _context.Entry(entity).State = EntityState.Detached;
         }

         // set Modified flag in your entry
         _context.Entry(entity).State = EntityState.Modified;

         // save 
         var result = _context.SaveChanges(); // Getting error while saving

         if (result > 0)
         {
             return new CreateBankResponse(entity.intBankID, entity.txtBankName, entity.txtBankCode, true, null);
         }
         else
         {
             return new CreateBankResponse(entity.intBankID, entity.txtBankName, entity.txtBankCode, false, new string[] { "Bank Registration failed." });
         }
     }
     catch (DbUpdateException e)
     {
         return new CreateBankResponse(0, string.Empty, string.Empty, false, new string[] { e.Message, e.InnerException.Message });
     }
     catch (DbEntityValidationException e)
     {
         return new CreateBankResponse(0, string.Empty, string.Empty, false, new string[] { e.Message, e.InnerException.Message });
     }
 }
.net asp.net-mvc entity-framework entity-framework-6
1个回答
0
投票

我建议使用AutoMapper.Collection

通过以下方式启用库:

Mapper.Initialize(cfg =>
{
    cfg.AddCollectionMappers();
    // Configuration code
});

EqualityComparison
添加到映射集合项。我不知道你用的是哪些类,所以我就以我自己的类为例。

cfg.CreateMap<MstBankDomain, FHASMstBankDomain>().EqualityComparison((odto, o) => odto.Id == o.Id);
cfg.CreateMap<MstBankProducts, FHASMstBankProducts>().EqualityComparison((odto, o) => odto.Id == o.Id);

然后将您的代码简化为

Map
。您不需要任何状态操作:

public CreateBankResponse UpdateBank(Bank bank)
{
    try
    {
        // load entity from database, if it is still not loaded
        var entity = _context.Set<FHASMstBank>().Find(bank.intBankID);

        if (entity == null)
        {
            // map DTO to new entity
            entity = _mapper.Map<FHASMstBank>(bank);
            _context.Set<FHASMstBank>().Add(entity);
        }
        else 
        {
            // map DTO to existing entity with collections
            _mapper.Map(bank, entity);
        }

        // save 
        var result = _context.SaveChanges(); // Getting error while saving

        if (result > 0)
        {
            return new CreateBankResponse(entity.intBankID, entity.txtBankName, entity.txtBankCode, true, null);
        }
        else
        {
            return new CreateBankResponse(entity.intBankID, entity.txtBankName, entity.txtBankCode, false, new string[] { "Bank Registration failed." });
        }
    }
    catch (DbUpdateException e)
    {
        return new CreateBankResponse(0, string.Empty, string.Empty, false, new string[] { e.Message, e.InnerException.Message });
    }
    catch (DbEntityValidationException e)
    {
        return new CreateBankResponse(0, string.Empty, string.Empty, false, new string[] { e.Message, e.InnerException.Message });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.