3
In some Orms Nodejs I have this feature. However, I would like to know how to rescue an entity that was persisted in the bank?
For example:
User
has an attribute ID
.
If I return the item, the ID
what has been persisted does not come within item
.
I would like to return something from _context of what was persisted, so that I come to rescue Id.
Follows a generic model I’m using:
public T Create(T item)
{
_dataset.Add(item);
_context.SaveChanges();
return item;
}
Follows class with basic methods:
public class GenericRepository<T> : IRepository<T> where T : BaseEntity
{
protected readonly AimbraDocContext _context;
private readonly DbSet<T> _dataset;
public GenericRepository(AimbraDocContext context)
{
_context = context;
_dataset = _context.Set<T>();
}
public T Create(T item)
{
_dataset.Add(item);
_context.SaveChanges();
return item;
}
public void Delete(long id)
{
var result = _dataset.SingleOrDefault(i => i.Id.Equals(id));
if (result != null)
{
_dataset.Remove(result);
_context.SaveChanges();
}
}
public bool Exist(long? id)
{
return _dataset.Any(i => i.Id.Equals(id));
}
public List<T> FindAll()
{
return _dataset.ToList();
}
public T FindById(long id)
{
var result = _dataset.SingleOrDefault(i => i.Id.Equals(id));
if (result == null) return null;
return result;
}
public T Update(T t)
{
if (!Exist(t.Id)) return null;
var result = _dataset.SingleOrDefault(i => i.Id.Equals(t.Id));
_context.Entry(result).CurrentValues.SetValues(t);
_context.SaveChanges();
return t;
}
}
The ID is auto increment in your base?
– novic
This... is yes... I defined it with the Dataanottation [Key] in na Prop Id.
– Thiago Cunha
You have to put all the code Create is very strange
– novic
If you are using
entity framework
and auto increment field, theitem.ID
should be completed after theSaveChanges
. Which database are you using? And post the class codeUser
.– Tiedt Tech
It is a generic class. I will update and if you have any changes, feel free to do with the observations. I am starting now in the language...
– Thiago Cunha
Your question has been answered here. In summary, EF6 already implements Insert with SCOPE_IDENTITY, just capture the object id.
– Mateus Roman
Ah... thank you! I got it here! :)
– Thiago Cunha
Someone can answer in Portuguese. I can’t close the question, because the platform requires an answer in Portuguese.
– Thiago Cunha