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. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM