Reputation: 578
What is the best solution in entity framework to implement generic persist method?
For example there is a Company entity:
public class Company
{
public Company()
{
Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public string Name { get; set; }
}
The Id property can be generated before entity is stored into the Database.
So the task is to implement Persist method:
public class Repository
{
private DbSet<Company> _dbSet;
public void Persist(Company company)
{
// How to implement body here to Add entity if it doesn't exists yet
// or Modify it in opposit case?
// In terms of database entity record is required to be inserted or updated.
}
}
Thanks!
Upvotes: 2
Views: 795
Reputation: 177133
In your example where you can't recognize if a Company
instance is new or has been formerly loaded from the database you must query the DB:
public void Persist(Company company)
{
var companyInDb = _dbSet.SingleOrDefault(c => c.Id == company.Id);
if (companyInDb != null)
{
_context.Entry(companyInDb).CurrentValues.SetValues(company);
}
else
{
_dbSet.Add(company);
}
_context.SaveChanges();
}
As you can see, you need a reference to the context _context
in your repository.
An alternative approach is possible if you mark the company as new or loaded from the DB, for example with a special constructor:
public class Company
{
public Company()
{
}
public Company(bool isNew)
{
Id = Guid.NewGuid();
_isNew = isNew;
}
public Guid Id { get; set; }
public string Name { get; set; }
private bool _isNew;
public IsNew { get { return _isNew; } }
}
The Persist
method wouldn't then need to load the original:
public void Persist(Company company)
{
if (!company.IsNew)
{
_context.Entry(company).State = EntityState.Modified;
}
else
{
_dbSet.Add(company);
}
_context.SaveChanges();
}
Note that all this only updates scalar properties of the company, not relationships.
Upvotes: 4