自定义属性属性

时间:2013-12-21 09:05:47

标签: c#

考虑以下函数,它只是为Object生成一个Sql UpdateCommand

public static string UpdateCommand<T>(this T obj,string idPropertyName, List<string> Except = null, List<string> Only = null)
{
    List<PropertyInfo> properties = FilterPropertyList<T>(Except, Only);

    StringBuilder query = new StringBuilder();
    query.Append("UPDATE " + typeof(T).Name + " SET ");
    for (int i = 0; i < properties.Count; i++)
    {
        if (idPropertyName.ToLower() == properties[i].Name.ToLower()) 
            continue;
        query.Append("[" + properties[i].Name + "] = @" + properties[i].Name + ",");
    }
    if (properties.Count > 1) 
    { 
        query.Length -= 2; 
    }
    query.Append(" WHERE " + idPropertyName + "=@" + idPropertyName);
    return query.ToString();
}

第二个参数只是属性名称,它引用了表示Sql表中主键的属性名称,我想知道它是否可以用属性信息中可用的属性来表示该属性,这个我不必将其作为参数发送。

如果这是我的对象

public class SomeObject
{
    //add a custom attribute to the id so it would be recognized in the above function without having to send the property name as a parameter
    public int id {get;set;}

    public string name {get;set}

}

以下是我如何使用SomeObject实例的函数

var someObject = new SomeObject();
var someObjectUpdateCommandString = someObject.UpdateCommand<SomeObject>("id");

我可以使用一些内置属性,还是创建自己的属性更好? 这是我的尝试,不确定它的写入和我似乎无法使用它

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    class IsPrimaryKey : Attribute
    {
        public IsPrimaryKey()
        {
            this.isPrimaryK = true;
        }

        private bool isPrimaryK;
        public virtual bool IsPrimaryK
        {
            get { return isPrimaryK; }
            set { isPrimaryK = value; }
        }
    }

1 个答案:

答案 0 :(得分:1)

属性类的名称应以Attribute后缀结尾。

通常,重用现有注释是一个好主意,如果它们具有您正在寻找的目的,并且不会引起不必要的依赖。

在您的情况下,在.NET 4.0中添加的System.ComponentModel.DataAnnotations.KeyAttribute属性可能会满足您的目的。

相关问题