#Entity
Framework   #C Sharp 
在Entity Framework 如果要直接下一些Sql指令,必要條件當然是要知道 Table name,
將Table Name寫死在程式當然是最不好的方式; 可以利用以下代碼取得DAO對應的Table Name。
▋使用 System.Data.Entity.DbContext
extension
| 
/// <summary> 
///
  DbContext/ObjectContext extensions 
/// </summary> 
public static class ContextExtensions 
{ 
        /// <summary> 
        /// Get the table name of Entity 
        /// </summary> 
        /// <typeparam name="T">Entity's type</typeparam> 
        /// <param name="context">DbContext</param> 
        /// <returns>Table name</returns> 
        public static string GetTableName<T>(this DbContext context) where T : class 
        { 
            ObjectContext objectContext =
  ((IObjectContextAdapter)context).ObjectContext; 
            return
  objectContext.GetTableName<T>(); 
        } 
        /// <summary> 
        /// Get the table name of Entity 
        /// </summary> 
        /// <typeparam name="T">Entity's type</typeparam> 
        /// <param name="context">ObjectContext</param> 
        /// <returns>Table name</returns> 
        public static string GetTableName<T>(this ObjectContext context) where T : class 
        { 
            string sql =
  context.CreateObjectSet<T>().ToTraceString(); 
            Regex regex = new Regex("FROM
  (?<table>.*) AS"); 
            Match match =
  regex.Match(sql); 
            string table =
  match.Groups["table"].Value; 
            return table; 
        } 
} | 
使用方式:
| 
var targetTableName = this._dbContext.GetTableName<MyEntity>(); | 
▋定義 [Table(“”)]
在Entity Framework Code first中, 通常會定義 [Table("XXXX")] 在DAO (Entity) 類別上。
| 
[Table("MyEntities")] 
public class MyEntity : BaseEntity 
{  … | 
這時候就可以使用 typeof(T).GetCustomAttributes 方法, 取得T類別定義的Class attributes。 
代碼如下:
| 
var attr
  =  
       typeof(T).GetCustomAttributes(false).Where(x =>
  x.GetType().Name.Equals("TableAttribute")).FirstOrDefault(); 
if (attr
  != null) 
{ 
    this._tableName = (attr as
  System.ComponentModel.DataAnnotations.Schema.TableAttribute).Name; 
} 
else 
{ 
     throw new Exception("Cannot get the table name of
  POCO : AdOU"); 
} | 
 
沒有留言:
張貼留言