InsertOnSubmit
是一种 Linq-to-SQL 方法,不在实体框架中。
然而,由于我们的项目是从 Linq 到 SQL 的转换,我们有一些扩展方法可能会有所帮助:
public static class ObjectContextExtensions
{
public static void SubmitChanges(this ObjectContext context)
{
context.SaveChanges();
}
public static void InsertOnSubmit<T>(this ObjectQuery<T> table, T entity)
{
table.Context.AddObject(GetEntitySetName(table.Context, entity.GetType()), entity);
}
public static void InsertAllOnSubmit<T>(this ObjectQuery<T> table, IEnumerable<T> entities)
{
var entitySetName = GetEntitySetName(table.Context, typeof(T));
foreach (var entity in entities)
{
table.Context.AddObject(entitySetName, entity);
}
}
public static void DeleteAllOnSubmit<T>(this ObjectQuery<T> table, IEnumerable<T> entities) where T : EntityObject, new()
{
var entitiesList = entities.ToList();
foreach (var entity in entitiesList)
{
if (null == entity.EntityKey)
{
SetEntityKey(table.Context, entity);
}
var toDelete = (T)table.Context.GetObjectByKey(entity.EntityKey);
if (null != toDelete)
{
table.Context.DeleteObject(toDelete);
}
}
}
public static void SetEntityKey<TEntity>(this ObjectContext context, TEntity entity) where TEntity : EntityObject, new()
{
entity.EntityKey = context.CreateEntityKey(GetEntitySetName(context, entity.GetType()), entity);
}
public static string GetEntitySetName(this ObjectContext context, Type entityType)
{
return EntityHelper.GetEntitySetName(entityType, context);
}
}
EntityHelper
根据 MyExtensions开源库在哪里。