Equivalent to ObjectContext.AddObject (entityName, entity) in DbContext
I have updated an old project running in ef4
, but now I have migrated 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 have updated almost all the code except:, context.AddObject(typeof(T).Name + "s", entity);
but this is no longer supported.
How can I update this?
ps I want to use generic code and not use switches to add the appropriate object to fix the ObjectSet
postscript Error if I use .Set (). Add (entity):
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
source to share
With DbContext, you can use context.Set<T>().Add(entity)
;
Example: context.Set<User>()
Equivalent context.Users
, therefore context.Set<User>().Add(myUser)
Equivalent context.Users.Add(myUser)
.
You need something closer:
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;
}
}
}
source to share