脚本,为当前模型创建所有表
/// </summary>
/// <returns>A SQL script</returns>
public virtual string GenerateCreateScript()
{
return this.Database.GenerateCreateScript();
}
/// <summary>
/// 基于原始SQL查询为查询类型创建LINQ查询
/// </summary>
/// <typeparam name="TQuery">Query type</typeparam>
/// <param name="sql">The raw SQL query</param>
/// <returns>An IQueryable representing the raw SQL query</returns>
public virtual IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class
{
return this.Query<TQuery>().FromSql(sql);
}
/// <summary>
///基于原始SQL查询为实体创建LINQ查询
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
/// <param name="sql">The raw SQL query</param>
/// <param name="parameters">The values to be assigned to parameters</param>
/// <returns>An IQueryable representing the raw SQL query</returns>
public virtual IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity
{
return this.Set<TEntity>().FromSql(CreateSqlWithParameters(sql, parameters), parameters);
}
/// <summary>
/// 对数据库执行给定的SQL
/// </summary>
/// <param name="sql">The SQL to execute</param>
/// <param name="doNotEnsureTransaction">true - the transaction creation is not ensured; false - the transaction creation is ensured.</param>
/// <param name="timeout">The timeout to use for command. Note that the command timeout is distinct from the connection timeout, which is commonly set on the database connection string</param>
/// <param name="parameters">Parameters to use with the SQL</param>
/// <returns>The number of rows affected</returns>
public virtual int ExecuteSqlCommand(RawSqlString sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
{
//set specific command timeout
var previousTimeout = this.Database.GetCommandTimeout();
this.Database.SetCommandTimeout(timeout);
var result = 0;
if (!doNotEnsureTransaction)
{
//use with transaction
using (var transaction = this.Database.BeginTransaction())
{
result = this.Database.ExecuteSqlCommand(sql, parameters);
transaction.Commit();
}
}
else
result = this.Database.ExecuteSqlCommand(sql, parameters);
//return previous timeout back
this.Database.SetCommandTimeout(previousTimeout);
return result;
}
/// <summary>
/// 从上下文中分离一个实体
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
/// <param name="entity">Entity</param>
public virtual void Detach<TEntity>(TEntity entity) where TEntity : BaseEntity
{
if (entity == null)
throw new ArgumentNullException(nameof(entity));
var entityEntry = this.Entry(entity);
if (entityEntry == null)
return;
//set the entity is not being tracked by the context
entityEntry.State = EntityState.Detached;
}
#endregion
}
代码都是从nop开源项目出抠出来的
|