#pragma warning disable CS0618 // Type or member is obsolete public IndexBuilderArgument(PrimaryKeyAttribute primaryKeyAttr, params string[] propertyNames) #pragma warning restore CS0618 // Type or member is obsolete { this.PropertyNames = propertyNames; this.IndexName = primaryKeyAttr.Name; this.IsClustered = primaryKeyAttr.IsClustered; }
public static MemberMapper[] GetKeyFieldList <T>(this Type value) where T : class { string key = value.FullName; MemberMapper[] mmList = (MemberMapper[])_keyList[key]; if (mmList == null) { List <MemberMapper> list = new List <MemberMapper>(); foreach (MemberMapper mm in ObjectMapper <T> .Instance) { if (!mm.MapMemberInfo.SqlIgnore) { PrimaryKeyAttribute attr = mm.MapMemberInfo.MemberAccessor.GetAttribute <PrimaryKeyAttribute>(); if (attr != null) { //list.Insert(attr.Order - 1, mm); list.Insert(attr.Order + 1, mm); } } } mmList = list.ToArray(); _keyList[key] = mmList; } return(mmList); }
private PrimaryKey(IEntityInfo entity, PropertyInfo prop, PrimaryKeyAttribute pkAttribute) : base(entity, prop, pkAttribute) { _constraintName = new Lazy <string>(ComputeConstraintName); KeyScheme = pkAttribute.KeyScheme; NullPkValue = GetDefaultValue(PropertyInfo.PropertyType); }
/// <summary> /// /// </summary> /// <param name="p"></param> /// <param name="order">复合主键 顺序</param> /// <returns></returns> public static bool IsPK(MemberInfo p, out int order) { order = 0; var attrs = p.GetCustomAttributes(typeof(PrimaryKeyAttribute), true); PrimaryKeyAttribute defaultPK = null; #if !NETFX_CORE var countRes = attrs.Length > 0; if (countRes) { defaultPK = (PrimaryKeyAttribute)attrs[0]; } #else var countRes = return(attrs.Count() > 0); if (countRes) { defaultPK = (PrimaryKeyAttribute)attrs.First(); } #endif if (countRes && defaultPK != null) { order = defaultPK.Order; } return(countRes); }
//public static Table LoadFromDb(string tableName) //{ // return null; //} #region Methods private Table GetTableFromProperty(Type type) { var table = new Table(); table.TableName = type.Name; List <PropertyInfo> props = type.GetPrimitivePropertys(); foreach (PropertyInfo property in props) { var tt = property.GetCustomAttributes(true); PrimaryKeyAttribute columnMaperAttribute = property.GetCustomAttributes(true).OfType <PrimaryKeyAttribute>().FirstOrDefault(); IColumn t = columnMaperAttribute; if (t != null) { //主键 t.PropertyName = property.Name; t.PropertyType = property.PropertyType; table.Columns.Add(t); } else { table.Columns.Add(new Column { ColumnName = property.Name, PropertyName = property.Name }); } } return(table); }
/// <summary> /// 新增或修改 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public R SaveOrUpdate <T>(T t, string cols, bool needReturn, VerifyData <T> @delegateVerify) { R result = null; Type type = t.GetType(); int count = 0; //获取属性特性【特性里面包括其属性】 PrimaryKeyAttribute primaryKeyAttribute = type.GetPrimaryKey(); if (primaryKeyAttribute == null) { return(new R() { Successful = false, ResultHint = "获取主键发生错误" }); } //委托方法存在 直接调用 主要是验证是否可以新增或修改 if (@delegateVerify != null) { VerifyMessage verifyMessage = @delegateVerify.Invoke(t); if (verifyMessage.ExistError) { //MessageBox.Show("错误信息:" + verifyMessage.ErrorInfo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(new R() { Successful = false, ResultHint = verifyMessage.ErrorInfo }); } } object primaryKey = primaryKeyAttribute.Prop.GetValue(t); //新增 ==》实际是主键不存在 if (primaryKey == null || "0".Equals(primaryKey.ToString())) { count = baseDAL.Insert(t, cols, needReturn); if (needReturn) { primaryKeyAttribute.Prop.SetValue(t, count);//设置主键的值 } } else { //修改 count = baseDAL.Update(t, cols, null, WhereType.SQL, false); } result = count > 0 ? new R() { Successful = true, ResultValue = t }: new R() { Successful = false, ResultHint = "操作失败" }; return(result); }
private static void GetPrimaryKey(SqlModel model) { int i = 0; int length = model.Struction.Members.Count; MemberInfo[] members = model.Struction.Members.ToArray(); while (i < length) { if (model.PrimaryKey == null || model.PrimaryKey == string.Empty) { PrimaryKeyAttribute temp_PrimaryKeyAttributer = members[i].GetCustomAttribute <PrimaryKeyAttribute>(true); if (temp_PrimaryKeyAttributer != null) { model.PrimaryKey = members[i].Name; model.IsMaunally = temp_PrimaryKeyAttributer.IsManually; break; } } i += 1; } if (model.PrimaryKey != null && !model.IsMaunally) { model.IgnoreMembers.Add(model.PrimaryKey); } }
/// <summary> /// Creates a new TypeDefinition for the POCO Type specified using any attributes on the class to determine mappings. /// </summary> public AttributeBasedTypeDefinition(Type pocoType) { if (pocoType == null) { throw new ArgumentNullException("pocoType"); } _pocoType = pocoType; // Look for supported attributes on the Type and set any properties appropriately PrimaryKeyAttribute primaryKeyAttribute = pocoType.GetCustomAttributes <PrimaryKeyAttribute>(true).FirstOrDefault(); if (primaryKeyAttribute != null) { _primaryKeyColumns = primaryKeyAttribute.ColumnNames; } ExplicitColumnsAttribute explicitColumnsAttribute = pocoType.GetCustomAttributes <ExplicitColumnsAttribute>(true).FirstOrDefault(); if (explicitColumnsAttribute != null) { _explicitColumns = true; } TableNameAttribute tableNameAttribute = pocoType.GetCustomAttributes <TableNameAttribute>(true).FirstOrDefault(); if (tableNameAttribute != null) { _tableName = tableNameAttribute.Value; } }
private void GenGetPrimaryKeyFieldListEx(StringBuilder sb, Type type, List <string> generatedProperties, int outLang) { foreach (Type item in GetContractInterfaceTypes(type)) { GenGetPrimaryKeyFieldListEx(sb, item, generatedProperties, outLang); } foreach (PropertyInfo item in CoreHelper.GetPropertiesFromType(type)) { //暂不支持关联处理,所以是类则跳过 if (item.PropertyType.IsInterface) { continue; } if (!generatedProperties.Contains(item.Name)) { PrimaryKeyAttribute key = GetPropertyAttribute <PrimaryKeyAttribute>(item); if (key != null) { sb.Append((outLang == 0 ? "_" : "__") + "."); sb.Append(item.Name); sb.Append(", "); generatedProperties.Add(item.Name); } } } //去除最后的逗号 if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1); } }
/// <summary> /// 批量删除 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public bool Delete <T>(List <int> idList) { List <CommandInfo> commandInfos = new List <CommandInfo>(); if (idList == null || idList.Count <= 0) { return(false); } CommandInfo commandInfo = null; SqlModel deleteModel = null; string whereStr = ""; Type type = typeof(T); PrimaryKeyAttribute primaryKeyAttribute = type.GetPrimaryKey(); for (int i = 0; i < idList.Count; i++) { whereStr = string.Format("{0}='{1}'", primaryKeyAttribute.ColumnName, idList[i]); deleteModel = CreateSqlHelper.DeleteSqlByWhere <T>(whereStr); commandInfo = new CommandInfo() { CommendText = deleteModel.Sql, IsProcess = false, Params = deleteModel.SqlParameters }; commandInfos.Add(commandInfo); } return(SQLiteHelper.ExecuteTrans(commandInfos)); }
public void IfAttributeExistsOnObjectReturnsTrue() { var entity = new Entity(); var exists = PrimaryKeyAttribute.IsDefined(entity); Assert.IsTrue(exists); }
private void Action_AddPrimaryKeyInfo(TableInfo tableInfo, PropertyInfo propertyInfo, PrimaryKeyAttribute primaryKeyAttribute) { var columnInfo = new ColumnInfo(this, primaryKeyAttribute.PrimaryKeyName, propertyInfo.PropertyType, propertyInfo); tableInfo.AddPrimaryKey(columnInfo); }
public static TableMap BuildMapFromInstance(Type type, object instance) { PersistableClassAttribute persistableClassAttribute = GetAttributeFrom <PersistableClassAttribute>(type); if (persistableClassAttribute == null) { throw new ApplicationException("Instance was not marked with the Persistable attribute!"); } // Make sure a valid name is specified for the table name if (String.IsNullOrEmpty(persistableClassAttribute.TableName)) { persistableClassAttribute.TableName = type.Name + "s"; } // Find PK property var primaryKeyFields = GetPropertiesForAttribute <PrimaryKeyAttribute>(type).ToList(); if (primaryKeyFields.Count == 0) { throw new ApplicationException("Instance did not have a property marked with the PrimaryKey attribute!"); } if (primaryKeyFields.Count > 1) { throw new ApplicationException("Instance has more then one property marked with the PrimaryKey attribute!"); } // Todo: make sure the PK is nullable PrimaryKeyAttribute primaryKeyAttribute = GetAttributeFrom <PrimaryKeyAttribute>(primaryKeyFields[0]); // Make sure a valid name is specified for the primary key if (String.IsNullOrEmpty(primaryKeyAttribute.FieldName)) { primaryKeyAttribute.FieldName = primaryKeyFields[0].Name; } object value = instance == null ? null : primaryKeyFields[0].GetValue(instance, null); PropertyToken primaryKeyToken = new PropertyToken(primaryKeyAttribute.FieldName, value, primaryKeyFields[0].PropertyType); // Get columns to persist var columns = new List <PropertyToken>(); var columnProperties = GetPropertiesForAttribute <PersistAttribute>(type).ToList(); foreach (var columnProperty in columnProperties) { object columnValue = instance == null ? null : columnProperty.GetValue(instance, null); columns.Add(new PropertyToken(columnProperty.Name, columnValue, columnProperty.PropertyType)); } return(new TableMap { TableName = persistableClassAttribute.TableName, PrimaryKey = primaryKeyToken, Columns = columns }); }
public string InsertDefinition(string fileName, Object obj) { string query = "INSERT INTO " + library + "." + fileName + " "; string fields = "( "; string values = " VALUES ( "; Type firstType = obj.GetType(); foreach (PropertyInfo propertyInfo in firstType.GetProperties()) { // populating firld name list DBFieldAttribute dbField = null; PrimaryKeyAttribute primary = null; object[] attrs = propertyInfo.GetCustomAttributes(true); foreach (object attr in attrs) { dbField = (attr as DBFieldAttribute) != null ? attr as DBFieldAttribute : dbField; primary = (attr as PrimaryKeyAttribute) != null ? attr as PrimaryKeyAttribute : primary; } string value = (propertyInfo.PropertyType == typeof(decimal)) ? propertyInfo.GetValue(obj, null).ToString() : "'" + propertyInfo.GetValue(obj, null) + "'"; if (dbField != null) { fields = fields == "( " ? (fields + dbField.FieldName) : (fields + "," + dbField.FieldName); values = values == " VALUES ( " ? values + value : values + " , " + value; } } query = "INSERT INTO " + library + "." + fileName + " " + fields + " ) " + values + " )"; int success = -1; try { dbConnection.cmd.CommandText = query; dbConnection.cmd.CommandType = System.Data.CommandType.Text; success = dbConnection.cmd.ExecuteNonQuery(); } catch (Exception ex) { if (dbConnection.con.State == System.Data.ConnectionState.Open) { dbConnection.RollBack(); } return(ex.Message + " - Query :" + query); } finally { if (dbConnection.con.State == System.Data.ConnectionState.Open) { dbConnection.Commit(); } } utils.Logger(query); return((success == 1) ? "1" : "Error - Query:" + query); }
public DeserializeHelper(string tableName, string fields) { this.Highlight = null; this._TableName = tableName; if (fields == "*" || string.IsNullOrWhiteSpace(fields)) { fields = ""; } this._Fields = fields; string[] source = fields.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); Type typeFromHandle = typeof(T); PropertyInfo[] properties = typeFromHandle.GetProperties(); for (int i = 0; i < properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; PrimaryKeyAttribute primaryKeyAttribute = PrimaryKeyHelper.GetPrimaryKeyAttribute(propertyInfo); if (primaryKeyAttribute != null) { this.PrimaryKey = primaryKeyAttribute; } if (string.IsNullOrWhiteSpace(fields) || source.Contains(propertyInfo.Name.ToLower())) { this._PropertyList.Add(propertyInfo); } } if (!string.IsNullOrWhiteSpace(this._TableName)) { this._DataTableSchema = new DataTable(this._TableName); } else { this._DataTableSchema = new DataTable("QueryData"); } foreach (PropertyInfo current in this.PropertyList) { DataColumn column = new DataColumn(current.Name, current.PropertyType); this._DataTableSchema.Columns.Add(column); } if (!string.IsNullOrWhiteSpace(this._Fields)) { if (source.Contains("score")) { DataColumn column2 = new DataColumn("score", typeof(double)); this._DataTableSchema.Columns.Add(column2); } if (source.Contains("_version_")) { DataColumn column3 = new DataColumn("_version_", typeof(string)); this._DataTableSchema.Columns.Add(column3); } } }
public string Delete(string fileName, Object obj) { string delete = "DELETE FROM " + library + "." + fileName + " WHERE "; string whereCondition = ""; string query = ""; Type firstType = obj.GetType(); foreach (PropertyInfo propertyInfo in firstType.GetProperties()) { object[] attrs = propertyInfo.GetCustomAttributes(true); DBFieldAttribute dbField = null; PrimaryKeyAttribute pkField = null; foreach (object attr in attrs) { dbField = (attr as DBFieldAttribute) != null ? attr as DBFieldAttribute : dbField; pkField = (attr as PrimaryKeyAttribute) != null ? attr as PrimaryKeyAttribute : pkField; } if (dbField != null && pkField != null) { string value = propertyInfo.PropertyType == typeof(string) ? "'" + propertyInfo.GetValue(obj, null).ToString() + "'" : propertyInfo.GetValue(obj, null).ToString(); string condition = dbField.FieldName + "=" + value; condition = whereCondition == "" ? " " + condition : " AND " + condition; whereCondition += condition; } } query = delete + whereCondition; int success = -1; try { dbConnection.cmd.CommandText = query; dbConnection.cmd.CommandType = System.Data.CommandType.Text; success = dbConnection.cmd.ExecuteNonQuery(); } catch (Exception ex) { if (dbConnection.con.State == System.Data.ConnectionState.Open) { dbConnection.RollBack(); } return(ex.Message + " - Query :" + query); } finally { if (dbConnection.con.State == System.Data.ConnectionState.Open) { dbConnection.Commit(); } } utils.Logger(query); return((success >= 1) ? "1" : "Error - Query :" + query); }
/// <summary> /// 获取表的主键信息[PropertyInfo 扩展方法] /// </summary> /// <param name="prop"></param> /// <returns></returns> public static PrimaryKeyAttribute GetPrimaryKey(this PropertyInfo prop) { PrimaryKeyAttribute primaryKeyAttribute = prop.GetCustomAttribute <PrimaryKeyAttribute>(); if (primaryKeyAttribute != null) { primaryKeyAttribute.Prop = prop; } return(primaryKeyAttribute); }
public override int GetPrimaryKeyOrder(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet) { PrimaryKeyAttribute attr = member.GetAttribute <PrimaryKeyAttribute>(); if (attr != null) { isSet = true; return(attr.Order); } return(base.GetPrimaryKeyOrder(type, typeExt, member, out isSet)); }
private static void CheckIgnoredProperties(IConventionEntityType entityType, PrimaryKeyAttribute primaryKeyAttribute) { foreach (var propertyName in primaryKeyAttribute.PropertyNames) { if (entityType.Builder.IsIgnored(propertyName, fromDataAnnotation: true)) { throw new InvalidOperationException( CoreStrings.PrimaryKeyDefinedOnIgnoredProperty( entityType.DisplayName(), propertyName)); } } }
///<summary> /// 获取主键名 /// </summary> /// <param name="type"></param> /// <returns></returns> public static string GetPrimary(this Type type) { object[] attributes = type.GetCustomAttributes(false); foreach (var attr in attributes) { if (attr is PrimaryKeyAttribute) { PrimaryKeyAttribute primaryKeyAttr = attr as PrimaryKeyAttribute; return(primaryKeyAttr.Name); } } return(null); }
/// <summary> /// 判断主键是否自增 /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsIncrement(this Type type) { object[] attributes = type.GetCustomAttributes(false); foreach (var attr in attributes) { if (attr is PrimaryKeyAttribute) { PrimaryKeyAttribute primaryKeyAttr = attr as PrimaryKeyAttribute; return(primaryKeyAttr.autoIncrement); } } return(false); }
//获取数据库表名[Type 扩展方法]==> /// <summary> /// 获取主键 /// </summary> /// <param name="type"></param> /// <returns></returns> public static PrimaryKeyAttribute GetPrimaryKey(this Type type) { PropertyInfo[] props = type.GetProperties(); props = props.Where(p => p.IsPrimaryKey()).ToArray(); if (props != null && props.Length > 0) { PrimaryKeyAttribute primaryKeyAttribute = GetPrimaryKey(props[0]); return(primaryKeyAttribute); } return(null); }
/// <summary> /// 字段是主键 /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="p"></param> /// <returns></returns> public bool IsPrimaryKey <TEntity>(Expression <Func <TEntity, string> > p) { if (p.Body is MemberExpression) { MemberExpression me = p.Body as MemberExpression; PropertyInfo prop = me.Member as PropertyInfo; PrimaryKeyAttribute f = prop.GetAttribute <PrimaryKeyAttribute>(); return(f != null); } else { throw new Exception("属性类型不正确"); } }
//获取列名[PropertyInfo 扩展方法] /// <summary> /// 获取字段在数据库中是否存在 /// </summary> /// <param name="prop"></param> /// <returns></returns> public static bool IsExist(this PropertyInfo prop) { TableFieldAttribute tableFieldAttribute = GetColumnAttriBute(prop); if (tableFieldAttribute != null) { return(tableFieldAttribute.IsExist); } else { PrimaryKeyAttribute primaryKeyAttribute = prop.GetCustomAttribute <PrimaryKeyAttribute>(); return(primaryKeyAttribute != null); } }
public void CanGeneratePrimaryKey() { Type type = Assembly.GetExecutingAssembly().GetType("Debugging.Tests.ClassWithPK"); PropertyInfo property = type.GetProperty("PrimaryKeyProperty"); object[] propertyAttributes = property.GetCustomAttributes(typeof(PrimaryKeyAttribute), false); Assert.IsTrue(propertyAttributes.Length == 1, "Did not generate PrimaryKeyAttribute."); PrimaryKeyAttribute attribute = propertyAttributes[0] as PrimaryKeyAttribute; Assert.IsTrue(attribute.Generator == PrimaryKeyType.Native); Assert.IsTrue(attribute.Params == "params"); Assert.IsTrue(attribute.UnsavedValue == "unsavedValue"); }
//public static T[] QueryWithStoredProc2(string storedProc, params object[] storedProcParameters) //{ // List<T> all = new List<T>(); // DataTable dt = DatabaseHandler.ExecuteStoredProc(storedProc, storedProcParameters); // List<dynamic> dys = dt.AsDynamicEnumerable().ToList(); // foreach (dynamic dr in dys) // { // string columnName = dr.Username; // } // return all.ToArray(); //} private static void CopyParentArrayToChildProperty(DataRow parent, object child) { var childProperties = child.GetType().GetProperties(); foreach (var childProperty in childProperties) { try { object[] attrs = childProperty.GetCustomAttributes(false); bool hasBeenSet = false; foreach (object attr in attrs) { PrimaryKeyAttribute pkAttribute = attr as PrimaryKeyAttribute; if (pkAttribute != null) { string column = pkAttribute.Column; if (column != null) { childProperty.SetValue(child, parent[column]); hasBeenSet = true; break; } } PropertyAttribute propertyAttribute = attr as PropertyAttribute; if (propertyAttribute != null) { string column = propertyAttribute.Column; if (column != null) { childProperty.SetValue(child, parent[column]); hasBeenSet = true; break; } } } if (hasBeenSet) { continue; } childProperty.SetValue(child, parent[childProperty.Name]); } catch (Exception) { } } }
/// <summary> /// 获取实体映射数据库主键字段集 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static List <string> GetPrimaryKeyNameList <T>() where T : new() { Type type = typeof(T); List <string> result = new List <string>(); foreach (PropertyInfo propertyInfo in type.GetProperties()) { PrimaryKeyAttribute primaryKeyAttribute = (PrimaryKeyAttribute)propertyInfo.GetCustomAttribute(typeof(PrimaryKeyAttribute)); if (primaryKeyAttribute != null) { result.Add(GetColumnName(propertyInfo)); } } return(result); }
static PropertyData GetUserDefinedPropertyData(PropertyInfo info, PropertyInfo dbProp) { var isBlob = info.PropertyType.IsA <Blob>(); var targetProp = dbProp ?? info; var columnName = info.Name + "_FileName".OnlyWhen(isBlob); return(new PropertyData(isBlob) { IsAutoNumber = AutoNumberAttribute.IsAutoNumber(info), IsCustomPrimaryKey = PrimaryKeyAttribute.IsPrimaryKey(info), Name = columnName, ParameterName = columnName, PropertyInfo = targetProp, NonGenericType = IsNullableType(targetProp) ? Nullable.GetUnderlyingType(targetProp.PropertyType) : targetProp.PropertyType }); }
public static object GetKeyField <T>() { Type type = typeof(T); string str = ""; string name = type.Name; foreach (Attribute attribute2 in type.GetCustomAttributes(true)) { PrimaryKeyAttribute attribute = attribute2 as PrimaryKeyAttribute; if (attribute != null) { str = attribute.Name; } } return(str); }
public static string GetKeyField(string className) { Type type = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin", "LeeFuns.Entity.dll")).GetType(className); string str = ""; string name = type.Name; foreach (Attribute attribute2 in type.GetCustomAttributes(true)) { PrimaryKeyAttribute attribute = attribute2 as PrimaryKeyAttribute; if (attribute != null) { str = attribute.Name; } } return(str); }
/// <summary> /// Initializes a new instance of the <see cref="PrimaryKeyModel"/> class. /// </summary> /// <param name="propInfo">The prop info.</param> /// <param name="pkAtt">The pk att.</param> public PrimaryKeyModel(PropertyInfo propInfo, PrimaryKeyAttribute pkAtt) { this.propInfo = propInfo; this.pkAtt = pkAtt; }