EF 中获取 TableAttribute的值,即数据库中真实的表名
比如EF中我定义了这样一个实体:
- [Table(Name = "MyTableName")]
- public class MyClass
- {
- }
[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
- {
- }
- }