在linq中动态设置tableAttribute映射到sql

时间:2013-01-07 09:37:46

标签: c# sql linq mapping

我想知道是否可以动态设置linq类的表映射:

    [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.[Comfort 0601$Contact]")]
    public partial class Contact : INotifyPropertyChanging, INotifyPropertyChanged
    {
     ...

我想动态或以编程方式更改它的原因是因为我正在使用的数据库是由Navision创建的。表中有这些表所属的公司名称的前缀。因此,我希望能够更改该前缀。

    [global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.["+SPResources.Database.Company+"$Contact]")]

whit公司:

    public const string Company = "Comfort 0601";

我已经尝试了这个,但只有在我宣布公司为常数时它才有效。

公司之间的表格结构完全相同。只是这个名字和内容改变。

我希望有人可以就此提出一些建议。我也不确定它是否可能。

4 个答案:

答案 0 :(得分:2)

认为添加table-prefix的正确解决方案是使用SQL Server 2005(或更新版本),然后为每个必需的前缀创建db-user,并将每个db-user的默认架构从“dbo”更改为某些内容唯一的。

另一个解决方案是扩展现有的DataContext,使其能够在运行时“更正”MappingSource:

[Table]  // Look no name
public class DbRecord
{
    [Column(IsPrimaryKey=true)]
    public long Id { get; set; }
}

CustomDataContext.UpdateCustomTable(typeof(DbRecord), "DbTable");

using (CustomDataContext dc = new CustomDataContext(dbConnection))
{
    Table<DbRecord> dbTable = dc.GetTable<DbRecord>();
    var query = from item in dbTable;
}

这是自定义DataContext(我想可以很容易地改变它来为现有的表名添加前缀)(如果在多线程环境中,用ConcurrentDictionary替换字典):

public class CustomDataContext : DataContext
{
    static CustomMappingSource _sharedMappingSource = new CustomMappingSource();

    public static void UpdateCustomTable(Type rowType, string tableName)
    {
        _sharedMappingSource.UpdateCustomTable(rowType, tableName);
    }

    public CustomDataContext(System.Data.IDbConnection connection) : base(connection, _sharedMappingSource) { }
    public CustomDataContext(string fileOrServerOrConnection) : base(fileOrServerOrConnection, _sharedMappingSource) { }
}

internal class CustomMappingSource : MappingSource
{
    AttributeMappingSource mapping = new AttributeMappingSource();

    Dictionary<Type, string> _customTableNames = new Dictionary<Type, string>();

    public void UpdateCustomTable(Type rowType, string tableName)
    {
        if (string.IsNullOrEmpty(tableName))
            throw new ArgumentNullException("TableName");

        _customTableNames[rowType] = tableName;
    }

    protected override MetaModel CreateModel(Type dataContextType)
    {
        MetaModel oldmodel = mapping.GetModel(dataContextType);
        CustomMetaModel newmodel = new CustomMetaModel(oldmodel, _customTableNames);
        return newmodel;
    }
}

internal class CustomMetaModel : MetaModel
{
    MetaModel _orgmodel;

    Dictionary<Type, MetaTable> _customtables = new Dictionary<Type, MetaTable>();
    Dictionary<Type, string> _tableNames = new Dictionary<Type, string>();

    public CustomMetaModel(MetaModel orgmodel, Dictionary<Type, string> tableNames)
    {
        _orgmodel = orgmodel;
        _tableNames = tableNames;
    }

    public override MetaType GetMetaType(Type type)
    {
        MetaTable metaTable;
        if (_customtables.TryGetValue(type, out metaTable))
            return metaTable.RowType;
        else
            return _orgmodel.GetMetaType(type);
    }
    public override MetaTable GetTable(Type rowType)
    {
        MetaTable customMetaTable;
        if (_customtables.TryGetValue(rowType, out customMetaTable))
            return customMetaTable;

        if (_tableNames.ContainsKey(rowType))
        {
            MetaTable orgtable = _orgmodel.GetTable(rowType);
            MetaType orgrowtype = orgtable.RowType;
            CustomMetaType newRowType = new CustomMetaType(orgrowtype, this);
            _customtables.Add(rowType, new CustomMetaTable(orgtable, this, newRowType, _tableNames[rowType]));
            newRowType.MetaTable = _customtables[rowType];
            return newRowType.MetaTable;
        }

        return _orgmodel.GetTable(rowType);
    }

    #region MetaModel Forwards
    public override Type ContextType { get { return _orgmodel.ContextType; } }
    public override string DatabaseName { get { return _orgmodel.DatabaseName; } }
    public override MappingSource MappingSource { get { return _orgmodel.MappingSource; } }
    public override Type ProviderType { get { return _orgmodel.ProviderType; } }
    public override MetaFunction GetFunction(System.Reflection.MethodInfo method) { return _orgmodel.GetFunction(method); }
    public override IEnumerable<MetaFunction> GetFunctions() { return _orgmodel.GetFunctions(); }
    public override IEnumerable<MetaTable> GetTables() { return _orgmodel.GetTables(); }
    #endregion
}

internal class CustomMetaTable : MetaTable
{
    MetaTable _orgtable;
    MetaModel _metamodel;
    MetaType _rowtype;
    string _tableName;

    public CustomMetaTable(MetaTable orgtable, MetaModel metamodel, MetaType rowtype, string tableName)
    {
        _orgtable = orgtable;
        _metamodel = metamodel;
        _rowtype = rowtype;
        _tableName = tableName;
    }

    public override MetaModel Model { get { return _metamodel; } }
    public override MetaType RowType { get { return _rowtype; } }
    public override string TableName { get { return _tableName; } }

    #region MetaTable Forwards
    public override System.Reflection.MethodInfo DeleteMethod { get { return _orgtable.DeleteMethod; } }
    public override System.Reflection.MethodInfo InsertMethod { get { return _orgtable.InsertMethod; } }
    public override System.Reflection.MethodInfo UpdateMethod { get { return _orgtable.UpdateMethod; } }
    #endregion
}

internal class CustomMetaType : MetaType
{
    MetaType _orgtype;
    MetaModel _metamodel;

    public MetaTable MetaTable { get; set; }

    public CustomMetaType(MetaType orgtype, MetaModel metamodel)
    {
        _orgtype = orgtype;
        _metamodel = metamodel;
    }

    public override MetaTable Table { get { return MetaTable; } }
    public override MetaModel Model { get { return _metamodel; } }

    #region MetaType Forwards
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaAssociation> Associations { get { return _orgtype.Associations; } }
    public override bool CanInstantiate { get { return _orgtype.CanInstantiate; } }
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaDataMember> DataMembers { get { return _orgtype.DataMembers; } }
    public override MetaDataMember DBGeneratedIdentityMember { get { return _orgtype.DBGeneratedIdentityMember; } }
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaType> DerivedTypes { get { return _orgtype.DerivedTypes; } }
    public override MetaDataMember Discriminator { get { return _orgtype.Discriminator; } }
    public override bool HasAnyLoadMethod { get { return _orgtype.HasAnyLoadMethod; } }
    public override bool HasAnyValidateMethod { get { return _orgtype.HasAnyValidateMethod; } }
    public override bool HasInheritance { get { return _orgtype.HasInheritance; } }
    public override bool HasInheritanceCode { get { return _orgtype.HasInheritanceCode; } }
    public override bool HasUpdateCheck { get { return _orgtype.HasUpdateCheck; } }
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaDataMember> IdentityMembers { get { return _orgtype.IdentityMembers; } }
    public override MetaType InheritanceBase { get { return _orgtype.InheritanceBase; } }
    public override object InheritanceCode { get { return _orgtype.InheritanceCode; } }
    public override MetaType InheritanceDefault { get { return _orgtype.InheritanceDefault; } }
    public override MetaType InheritanceRoot { get { return _orgtype.InheritanceRoot; } }
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaType> InheritanceTypes { get { return _orgtype.InheritanceTypes; } }
    public override bool IsEntity { get { return _orgtype.IsEntity; } }
    public override bool IsInheritanceDefault { get { return _orgtype.IsInheritanceDefault; } }
    public override string Name { get { return _orgtype.Name; } }
    public override System.Reflection.MethodInfo OnLoadedMethod { get { return _orgtype.OnLoadedMethod; } }
    public override System.Reflection.MethodInfo OnValidateMethod { get { return _orgtype.OnValidateMethod; } }
    public override System.Collections.ObjectModel.ReadOnlyCollection<MetaDataMember> PersistentDataMembers { get { return _orgtype.PersistentDataMembers; } }
    public override Type Type { get { return _orgtype.Type; } }
    public override MetaDataMember VersionMember { get { return _orgtype.VersionMember; } }
    public override MetaDataMember GetDataMember(System.Reflection.MemberInfo member) { return _orgtype.GetDataMember(member); }
    public override MetaType GetInheritanceType(Type type) { return _orgtype.GetInheritanceType(type); }
    public override MetaType GetTypeForInheritanceCode(object code) { return _orgtype.GetTypeForInheritanceCode(code); }
    #endregion
}

答案 1 :(得分:1)

Brian和Gert的答案是解决这个问题的可能方法。但是在运行时更改映射是不可能的(正如Brian所说)。

随着我们项目的进展,我们决定如果我们需要另一个公司名称(这意味着该构建是针对不同的客户),我们将重建项目。该决定使以下解决方案成为可能:

我们注释掉了Visual Studio生成的原始映射:

//[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.[Comfort 0601$Contact]")]
    public partial class Contact : INotifyPropertyChanging, INotifyPropertyChanged
    {
    ...

因为我们为每个Linq类都有自己的部分类,所以我们在自己的类顶部添加了修改后的映射:

[global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.["+SPResources.Database.Company+"$Contact]")]
public partial class Contact
{

我们公司将在哪里:

public const string Company = "Comfort 0601";

如果其他公司需要重建,我们只需更改公司变量。

注意:只有在VS中不更改* .dbml文件时,此方法才能正常工作。如果这样做,VS将自动撤消您的更改。

修改:随着时间的推移,我开始更多地了解实体框架,我找到了针对此问题的更具体,更合适的解决方案:http://www.codeproject.com/Articles/421643/How-to-Use-MVC-Net-on-the-Dynamics-NAV-Database-St

答案 2 :(得分:0)

您可以使用SQLMetal为每个实体自定义生成代码。您无法在运行时动态应用属性,因此这是最佳选择。

答案 3 :(得分:0)

如果您首先使用代码工作,则可以使用fluent mapping,您可以使用ToTable()方法在运行时配置数据库表(请参阅更改数据库表名称)。例如。在OnModelCreating()覆盖您的DbContext派生词:

string company = "Comfort 0601";
modelBuilder.Entity<Contact>().ToTable(company + "Contact");
modelBuilder.Entity<....
modelBuilder.Entity<....

您可以从配置文件中获取公司名称。