实体框架6,存储库模式,工作单元,保存并获取最后一个ID,然后更新记录

问题描述 投票:-1回答:2

我接管了一个使用EF6,Repository模式,工作单元的MVC Web项目。我刚开始学习EF6。

我想创建一个新组织并将其保存到数据库,然后获取新的组织ID。新组织ID将用于重命名将存储在organisation.logo中的图像文件。然后使用新文件名更新数据库中的组织徽标字段。

我有组织保存,获取新的组织ID,重命名文件,但我无法更新徽标字段?

代码如下:

组织控制器 - 显示基本代码我删除了很多验证并重命名了图像文件。

public ActionResult Create(OrganisationViewModel viewModelToCreate)
    {

        Organisation newOrganisation = new Organisation();
        newOrganisation.Name = viewModelToCreate.Name;
        newOrganisation.Logo = "To Change";

        _Uow.OrganisationRepository.InsertOrUpdate(newOrganisation);

        if (ModelState.IsValid)
        {
            _Uow.Save();
            int newOrganisationId = _Uow.OrganisationRepository.LastInsertedID();
            Organisation organisationToUpdate = _Uow.OrganisationRepository.Find(newOrganisationId);
string fileName = newOrganisationId.ToString() + Path.GetExtension(viewModelToCreate.FileNameToAdd.FileName);

                organisationToUpdate.Logo = fileName;
                _Uow.OrganisationRepository.InsertOrUpdate(organisationToUpdate);
                _Uow.Save();
            }

    }


public virtual T InsertOrUpdate(T e)
    {
        DbSet<T> dbSet = Context.Set<T>();

        DbEntityEntry<T> entry;
        if (e.ID != default(int))
        {
            entry = Context.Entry(e);

        }
        else
        {
            T instance = dbSet.Create();
            instance.ID = e.ID;
            entry = Context.Entry(instance);
            dbSet.Attach(instance);
            entry.CurrentValues.SetValues(e);
            e = instance;
        }

        entry.State = e.ID == default(int) ?
                                EntityState.Added :
                                EntityState.Modified;

        return e;
    }


     int IUnitOfWork.Save()
        {

                return _Context.SaveChanges();
     }

      public int LastInsertedID()
         {
             Context = new aContext();
             int newOrganisationId = Context.Organisations.OrderByDescending(x => x.ID).FirstOrDefault().ID;
             return newOrganisationId;
    }

如何使用新文件名更新组织To Update.Logo,它不保存到数据库?

entity-framework-6 repository-pattern unit-of-work
2个回答
1
投票

由于您尚未共享UoW和Repository方法,因此我们无法知道代码中究竟发生了什么。但是,我提供了所需的代码,可以满足您的需要,而无需考虑Repository和UoW。只需检查您的代码是否执行以下操作:

var db = new AppDbContext();

// inserting new organization
Organisation newOrganisation = new Organisation();
newOrganisation.Name = viewModelToCreate.Name;
newOrganisation.Logo = "To Change";
db.Organisation.Add(newOrganisation);
db.SaveChanges();

// updating the inserted organization
string fileName = ”New FileName”;
newOrganisation.Logo = fileName;
db.SaveChanges();

0
投票

您需要两次调用[UOW.Save]方法。像你一样打电话给第一个。完成后,您保存的实体将使用在数据库中分配的Id进行更新。然后添加带有该Id的代码,并根据需要将其添加到文件名中。如果这不起作用,那么你的UOW或Repository会出现问题,导致它无法正常工作。顺便说一句,UOW和Repository是“模式”而不是实现,所以我们不能期望知道代码是什么样的以及它是如何工作的,如果你想要问题,你需要更准确地了解你正在做什么回答

© www.soinside.com 2019 - 2024. All rights reserved.