【问题标题】:get Scope ID in entity framework 6 after saving data保存数据后在实体框架 6 中获取 Scope ID
【发布时间】:2016-06-23 10:08:22
【问题描述】:

我已经在数据访问层之上实现了存储库模式和工作单元。我在通用存储库中有所有的 crud 操作,但在工作单元中保存方法。在我的业务类中,我将对象传递给泛型类,然后是工作单元中的 Save 方法,我的问题是我如何从现在开始获取范围 ID

基本上我需要在保存后获取对象的 ID,因为我使用泛型类来保存数据,所以我不知道对象 ID 名称是什么

 public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
 protected DbSet<TEntity> _DbSet;
    private readonly DbContext _dbContext;

    public GenericRepository()
    { }

    public GenericRepository(DbContext dbContext)
    {
        this._dbContext = dbContext;
        _DbSet = _dbContext.Set<TEntity>();
    }

    public void InsertEntity(TEntity obj)
    {
        _DbSet.Add(obj);
    }
}

...

 public class FunctionsNavigation_UnitOfWork : IDisposable
{
    private FunctionContext _FunctionContext = new FunctionContext();

    uow.Qualification_FeeSchemeRepository.InsertEntity(obj);
 }
}

  public void Save()
    {
        _FunctionContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

        _FunctionContext.SaveChanges();

    }

在保存后的商务舱中,我尝试获取对象的 ID,但我没有得到任何东西

  _uof.Sys_Nav_Functions_Repository.InsertEntity(_Sys_Nav_FunctionEntity);


   _uof.Save();

   _FunctionID = _obj.Sys_Nav_Function.Function_ID;

【问题讨论】:

    标签: c# entity-framework-6 repository-pattern unit-of-work


    【解决方案1】:

    您将在对象本身获得插入的Id

    private FunctionContext _FunctionContext = new FunctionContext();
    
    var obj = new yourEntity();
    uow.Qualification_FeeSchemeRepository.InsertEntity(obj);
    uow.Save();
    

    将数据保存到数据库后。实体框架将填充从数据库生成的实体类型 PK。

    总之你到这里

    int id = obj.Id;
    

    更新插入 1:1 关系示例

    Person person = new Person//create person entity
    {
       FirstName = "Eldho",
       LastName  = "Abe",
    };
    
    AuthorizedUser user = new AuthorizedUser//create authorized user role entity
    {
       Person = person, //The reference of newly inserted user
       UserId = myUserid,
       HashedPassword = password,
    };
    
    uow.PersonDA.Insert(person);
    uow.AuthorizedUserDA.Insert(user);
    
    uow.Save();//insert to database
    

    【讨论】:

    • 在某些 1:1 关系的情况下,我在依赖表中使用与主键和外键相同的键,有没有办法获得 true 或 false 返回以确保数据被保存
    • 如果你的外键约束无效,SaveChanges()肯定会抛出异常并回滚整个事务。我将在我的回答中更新一个典型场景
    • 我很高兴@toxic 快乐编码
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2014-06-07
    • 1970-01-01
    • 2022-12-03
    • 2017-12-10
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    相关资源
    最近更新 更多