Question:
In some ORMs NodeJs I have this feature. However, would you like to know how to rescue an entity that was persisted in the bank?
For example: User
has an ID
attribute. If I return the item, the persisted ID
doesn't come inside item
.
I would like to return something from the _context that was persisted, so that I can retrieve the Id.
Here's a generic template I'm using:
public T Create(T item)
{
_dataset.Add(item);
_context.SaveChanges();
return item;
}
Here's a 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;
}
}
Answer:
What you can do is instead of using the Id as an int you can use the GUID which will always give you a string.
Id = Guid.NewGuid();
That way you will always have a unique identifier and know what it is before registering with the bank.