zoukankan      html  css  js  c++  java
  • EF 中获取 TableAttribute的值,即数据库中真实的表名

     

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

    [csharp] view plain copy
     
    print?
    1. [Table(Name = "MyTableName")]  
    2. public class MyClass  
    3. {  
    4. }  
        [Table(Name = "MyTableName")]
        public class MyClass
        {
        }

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


     

    [csharp] view plain copy
     
    print?
    1. using System.Data.Linq.Mapping;  
    2.   
    3. namespace MyEF  
    4. {  
    5.     class Program  
    6.     {  
    7.         static void Main(string[] args)  
    8.         {  
    9.             string name = typeof(MyClass).GetAttributeValue((TableAttribute ta) => ta.Name);  
    10.             Console.WriteLine(name);  
    11.   
    12.             Console.Read();  
    13.         }  
    14.     }  
    15.   
    16.     public static class AttributeExtensions  
    17.     {  
    18.         public static TValue GetAttributeValue<TAttribute, TValue>(  
    19.             this Type type,  
    20.             Func<TAttribute, TValue> valueSelector)  
    21.             where TAttribute : Attribute  
    22.         {  
    23.             var att = type.GetCustomAttributes(  
    24.                 typeof(TAttribute), true  
    25.             ).FirstOrDefault() as TAttribute;  
    26.             if (att != null)  
    27.             {  
    28.                 return valueSelector(att);  
    29.             }  
    30.             return default(TValue);  
    31.         }  
    32.     }  
    33.   
    34.     [Table(Name = "MyTableName")]  
    35.     public class MyClass  
    36.     {  
    37.     }  
    38. }  
  • 相关阅读:
    windows下启动数据库、创建数据表、角色等
    直播流的来源
    win10如何查看已保存的账号信息
    Tomcat+IDEA
    线程安全-Spring Bean 作用域类型(Scope)
    ECMAScript6学习-2.1let与const
    解决Mac上Android开发时adb连接不到手机问题
    8个不可不知的Mac OS X专用命令行工具(转)
    ios 中获得应用程序名称和版本号
    iPhone 6 图像渲染揭秘(转)
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/5561723.html
Copyright © 2011-2022 走看看