/// <summary> /// 如果不满足条件则创建一个实体, /// 如限制用户名不能重复 InsertIfNotExist(user, u => u.Name == user.Name) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity">要创建的实体</param> /// <param name="where">条件</param> /// <returns>新生成记录的ID,若失败返回0</returns> public int InsertIfNotExists <T>(T entity, Expression <Func <T, bool> > where) where T : class, IEntity, new() { if (where == null) { return(Insert(entity)); } var entityInfo = MyEntityContainer.Get(typeof(T)); var resolver = new EditConditionResolver <T>(entityInfo); var result = resolver.Resolve(@where.Body); var condition = result.Condition; var parameters = result.Parameters; parameters.Add(entity); condition = string.IsNullOrWhiteSpace(condition) ? "1=1" : condition; var sqlBuilder = new SqlServerBuilder(); var sql = sqlBuilder.InsertIfNotExists(entityInfo, condition); var command = new SqlCommand(sql); command.Parameters.AddRange(parameters.Parameters); using (var conn = new SqlConnection(_connectionString)) { conn.Open(); command.Connection = conn; var obj = command.ExecuteScalar(); if (obj != DBNull.Value) { entity.Id = Convert.ToInt32(obj); } return(entity.Id); } }