簡體   English   中英

ADO.NET實體模型-動態分配TableAttribute

[英]ADO.NET Entity Model - Dynamically assigning TableAttribute

我需要一個允許用戶在配置文件中設置數據庫信息和表名的項目。 我想使用ADO.NET實體模型來使用LINQ,並盡我最大可能遠離SQL,以使其對我自己更容易。 有沒有一種方法可以動態分配類需要為模態訪問的表?

例如:這是通常的樣子

    [Table("database.table")]
    public partial class table
    {
        [Key]
        [Column(TypeName = "usmallint")]
        public int ID { get; set; }

        [Required]
        [StringLength(128)]
        public string Instance { get; set; }

        [Required]
        [StringLength(60)]
        public string Name { get; set; }
    }

我希望能夠動態設置TableAttribute,以便模型知道要訪問該類的表。

    [Table(Config.DBName + Config.tableName)]
    public partial class table
    {
        [Key]
        [Column(TypeName = "usmallint")]
        public int ID { get; set; }

        [Required]
        [StringLength(128)]
        public string Instance { get; set; }

        [Required]
        [StringLength(60)]
        public string Name { get; set; }
    }

任何幫助或讓我知道這是不可能的,將不勝感激。

我尚未對此進行測試,但是我認為您可以通過實現自定義約定來實現此目的-如果您至少使用EF6。

首先,您需要創建一個自定義約定:

public class CustomTableNameConvention : IStoreModelConvention<EntitySet>
{
    private readonly string _tablePrefix;

    public CustomTableNameConvention(string tablePrefix)
    {
        _tablePrefix = tablePrefix;
    }

    public void Apply(EntitySet item, DbModel model)
    {
        //change table name.
        item.Table = $"{_tablePrefix}" + item.Table;
    }
}

接下來,您需要在Context的OnModelCreating方法中添加此約定:

public class MyContext : DbContext
{
    public MyContext(string connectionString) : base(connectionstring)
    {
    } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //get the dynamic table prefix...
        var myAppPrefix = "user1";
        modelBuilder.Conventions.Add(new CustomTableNameConvention(myAppPrefix));
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<SomeModel> { get; set; }
    ...
}

...然后,只要此應用程序實例中的模型啟動,在決定表名應為何種形式時,它都應運行上述過程。 只需將myAppPrefix = ...代碼替換為對適當服務的調用即可獲取該實例的前綴。

明顯的警告是,您不能使用從數據庫返回的前綴的值(至少不是通過此Context),因為Context尚未初始化..因此,您必須存儲它在設置中或以其他方式傳遞。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM