I upgraded an old project started in ef4 but now I migrated it to ef5.
This is the old code:
protected void SaveEntity<T>(T entity)
{
using (DocsManagerContainer context = new DocsManagerContainer())
{
string entityType = typeof(T).ToString();
GetLogger().LogMessage("Save " + entityType + " started", LogLevel.Info);
DbTransaction transaction = null;
try
{
context.Connection.Open();
transaction = context.Connection.BeginTransaction();
context.AddObject(typeof(T).Name + "s", entity);
transaction.Commit();
context.SaveChanges();
}
catch (Exception e)
{
GetLogger().LogMessage("Save " + entityType + " thrown error :", e, LogLevel.Error);
throw e;
}
finally
{
context.Connection.Close();
transaction = null;
}
GetLogger().LogMessage("Save " + entityType + " ended", LogLevel.Info);
}
}
I've upgraded almost all of the code except : context.AddObject(typeof(T).Name + "s", entity);, but this isn't supported anymore.
How can I upgrade this ?
p.s. I do want to use generic code, not to use switches to add the corresponding object to correct ObjectSet
p.s. Error if I use .Set().Add(entity) is :
Error 2 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Entity.DbContext.Set<TEntity>()' D:\work\DocsManager\trunk\DocsManagerDataMapper\EF4Factory\BaseEF4Factory.cs 64 21 DocsManagerDataMapper
With DbContext you can use context.Set<T>().Add(entity);
Example: context.Set<User>() is equivalent to context.Users so context.Set<User>().Add(myUser) is equivalent to context.Users.Add(myUser).
You want something closer to this:
protected void SaveEntity<T>(T entity)
where T : class
{
using (DocsManagerContainer context = new DocsManagerContainer())
{
DbTransaction transaction = null;
try
{
context.Connection.Open();
transaction = context.Connection.BeginTransaction();
context.Set<T>().Add(entity);
transaction.Commit();
context.SaveChanges();
}
finally
{
context.Connection.Close();
transaction = null;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With