现在的位置: 首页 > 综合 > 正文

EF 中获取 TableAttribute的值,即数据库中真实的表名

2013年04月08日 ⁄ 综合 ⁄ 共 659字 ⁄ 字号 评论关闭

 

比如EF中我定义了这样一个实体:

 

    [Table(Name = "MyTableName")]
    public class MyClass
    {
    }

 

现我想获取 MyTableName,可以这样来办:

 

using System.Data.Linq.Mapping;

namespace MyEF
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = typeof(MyClass).GetAttributeValue((TableAttribute ta) => ta.Name);
            Console.WriteLine(name);

            Console.Read();
        }
    }

    public static class AttributeExtensions
    {
        public static TValue GetAttributeValue<TAttribute, TValue>(
            this Type type,
            Func<TAttribute, TValue> valueSelector)
            where TAttribute : Attribute
        {
            var att = type.GetCustomAttributes(
                typeof(TAttribute), true
            ).FirstOrDefault() as TAttribute;
            if (att != null)
            {
                return valueSelector(att);
            }
            return default(TValue);
        }
    }

    [Table(Name = "MyTableName")]
    public class MyClass
    {
    }
}

 

抱歉!评论已关闭.