Reputation: 5075
I have implemented repository pattern and unit of work on top of Data Access Layer. I have all the crud operation in Generic Repository but save method in unit of work. In my business class I am passing object to generic class, followed by Save method in unit of work, my question is how can i get scope ID from this point forward
Basically I need to get ID of object after saving where I don't know what is object ID name as I am using generic class to save data
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();
}
in following business class after saving I try to get ID on object but I am not getting any thing
_uof.Sys_Nav_Functions_Repository.InsertEntity(_Sys_Nav_FunctionEntity);
_uof.Save();
_FunctionID = _obj.Sys_Nav_Function.Function_ID;
Upvotes: 0
Views: 574
Reputation: 8273
You will get the inserted
Id
at the object itself.
private FunctionContext _FunctionContext = new FunctionContext();
var obj = new yourEntity();
uow.Qualification_FeeSchemeRepository.InsertEntity(obj);
uow.Save();
Once you save the data into the database. The entity-framework will fill the entity type PK that is generated from the database.
In short you get here
int id = obj.Id;
Update Inserting 1:1 Relationship Sample
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
Upvotes: 3