[英]Dynamic table name with entity framework
我有許多表具有相同的模型結構,但其他表名和其他數據(在這種情況下將是 ~100 個表)。 我想在運行時使用實體框架動態切換表名(例如從路由中獲取名稱表)。 數據庫中的表是由其他腳本動態添加和刪除的。 有一種方法可以像這樣具有良好的性能嗎?
db.Table("TableName")<SpecificModel>.Where(x => x.ID == ID)
你想這樣做嗎?
foreach (string tableName in new[] { "Table1", "Table2" })
{
var result = dbContext.Database.SqlQuery<SpecificModel>(string.Format("SELECT * FROM {0} WHERE ID=@p0", tableName), 1).FirstOrDefault();
}
我做了這樣的事。 http://nodogmablog.bryanhogan.net/2013/08/entity-framework-in-an-dynamics-nav-navision-envirnoment/
我有相同的表,但他們有不同的名字。 例如,客戶表但具有不同公司的不同前綴。
[ACME$Customer]
[SuperCorp$Customer]
我最終使用動態編譯。 這是一篇非常詳細的博客文章,所以我不會在這里討論它。
你可以這樣做:
// Gets entity type from specified namespace/assembly
Type entityType = Type.GetType(string.Format("Your.NameSpace.{0},{1}", entityName, "Assembly.Name"));
// Finds item to update based on its primary key value
var entity = _dbContext.Find(entityType, entityKey);
// Finds column to update preference for
PropertyInfo propertyInfo = entity.GetType().GetProperty(entityField);
// Set and update (date example given)
propertyInfo.SetValue(entity, isOptIn ? (DateTime?)null : (DateTimeOffset?)DateTime.Now, null);
_dbContext.SaveChanges();
var tableName = item.TableName;
Type entityType = Type.GetType(string.Format("AlbashaSweets.Models.{0}", tableName));
var data = _DBContext.Set(entityType);
//AlbashaSweets.Models is Your Namespace
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.