0

//嗨,下面的代码片段,我想根据模型的导航属性更改模型及其相关实体,但只影响模型比例属性。运行时没有异常。我不知道为什么,请帮助我,非常感谢!

public bool Update(Container model)
{
var  mExist=dbContext.Container.SingleOrDefault(m=>m.TransportDocumentId==model.TransportDocumen tId && m.ContainerNo==model.ContainerNo);
        if (mExist != null)
        {
            if (mExist.Id != model.Id)
            {
                throw new Exception("The same entity has been exist!.");
            }
            dbContext.Entry(mExist).State = EntityState.Detached;
        }


        var mOld = dbContext.Container.SingleOrDefault(m => m.Id == model.Id);
        string oldContainerNo = model.ContainerNo;
        if (mOld != null)
        {
            oldContainerNo = mOld.ContainerNo;
            dbContext.Entry(mOld).State = EntityState.Detached;
        }

        dbContext.Container.Attach(model);

        var mGoods = model.TransportDocument.Goods;
        if (model.ContainerNo != oldContainerNo)
        {

            foreach (var g in mGoods)
            {
                var gn = g.GoodsContainerNo.Where(n => n.ContainerNo == oldContainerNo);
                foreach (var gNo in gn)
                {
                    //WHY,here CHANGES cannot be save to datastore!!!
                    gNo.ContainerNo = model.ContainerNo;
                    dbContext.Entry(gNo).State = EntityState.Modified;
                }
            }
        } 

        dbContext.Entry(model).State = EntityState.Modified;

        return dbContext.SaveChanges() >= 0;
    }
4

0 回答 0