代码之家  ›  专栏  ›  技术社区  ›  Sam

如何在运行时创建XmlMappingSource?

  •  1
  • Sam  · 技术社区  · 17 年前

    (后续问题 How to change LINQ O/R-M table name/source during runtime? )

    XmlMappingSource 。在命令行上,我可以使用SqlMetal创建此映射文件,但我想在内存中的运行时创建映射文件。 XmlMappingSource是一个简单的xml文件,看起来像这样:

    <?xml version="1.0" encoding="utf-8"?>
    <Database Name="MyDatabase" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
      <Table Name="dbo.MyFirstTable" Member="MyFirstTable">
        <Type Name="MyFirstTable">
          <Column Name="ID" Member="ID" Storage="_ID" DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" />
          <Association Name="WaStaArtArtikel_WaVerPreisanfragen" Member="WaStaArtArtikel" Storage="_WaStaArtArtikel" ThisKey="ArtikelID" OtherKey="ID" IsForeignKey="true" />
        </Type>
      </Table>
      <Table Name="dbo.MySecondTable" Member="MySecondTable">
        <Type Name="MySecondTable">
          <Column Name="ID" Member="ID" Storage="_ID" DbType="UniqueIdentifier NOT NULL" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" />
          <Column Name="FirstTableID" Member="FirstTableID" Storage="_FirstTableID" DbType="UniqueIdentifier NOT NULL" />
          <Association Name="MySecondTable_MyFirstTable" Member="MyFirstTable" Storage="_MyFirstTable" ThisKey="FirstTableID" OtherKey="ID" IsForeignKey="true" />
        </Type>
      </Table>
    </Database>
    

    using System.Data.Linq.Mapping;
    using System.Xml.Linq;
    
    XDocument mapWriter = new XDocument();
    DatabaseAttribute[] catx = (DatabaseAttribute[])typeof(WcfInterface.WaDataClassesDataContext).GetCustomAttributes(typeof(DatabaseAttribute), false);
    XElement xDatabase = new XElement("Database");
    xDatabase.Add(new XAttribute("Name", catx[0].Name));
    mapWriter.Add(xDatabase);
    

    我的问题是:我找不到映射的好文档,所以提取必要的信息很容易出错——也许有人可以给我指一些映射的好文件,或者,更好的是,指一个如何创建映射文件的代码示例?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Richard    17 年前

        2
  •  1
  •   Scott Hanselman    17 年前

        3
  •  0
  •   cpoDesign    13 年前

    我需要更新解决方案中映射文件中的数据库名称。

    <?xml version="1.0" encoding="utf-8"?>
    <Database Name="DatabaseName" xmlns="http://schemas.microsoft.com/linqtosql/mapping/2007">
      <Table Name="dbo.tblDictionary" Member="TblDictionary">
        <Type Name="TblDictionary">
          <Column Name="lngRecordID" Member="LngRecordID" Storage="_LngRecordID" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" />
          <Column Name="txtWord" Member="TxtWord" Storage="_TxtWord" DbType="VarChar(50) NOT NULL" CanBeNull="false" />
        </Type>
      </Table>
    </Database>
    

    最后是代码:

    class Program
        {
            static void Main(string[] args)
            {
    
            // to get embeded file name you have to add namespace of the application
            const string embeddedFilename = "ConsoleApplication3.FrostOrangeMappings.xml";
            // load file into stream
            var embeddedStream = GetEmbeddedFile(embeddedFilename);
            // process stream
            ProcessStreamToXmlMappingSource(embeddedStream);
            Console.ReadKey();
    
    
        }
    
        private static void ProcessStreamToXmlMappingSource(Stream stream)
        {
    
            const string newDatabaseName = "pavsDatabaseName";      
    
            var mappingFile = new XmlDocument();
            mappingFile.Load(stream);
            stream.Close();
    
    
            // populate collection of attribues
            XmlAttributeCollection collection = mappingFile.DocumentElement.Attributes;
    
            var attribute = collection["Name"];
            if(attribute==null)
            {
                throw new Exception("Failed to find Name attribute in xml definition");
            }
    
            // set new database name definition
            collection["Name"].Value = newDatabaseName;
    
            //display xml to  user
            var stringWriter = new StringWriter();
              using (var xmlTextWriter = XmlWriter.Create(stringWriter))
              {
                  mappingFile.WriteTo(xmlTextWriter);
                  xmlTextWriter.Flush();
                  stringWriter.GetStringBuilder();
              }
            Console.WriteLine(stringWriter.ToString());
    
        }
        /// <summary>
        /// Loads file into stream
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static Stream GetEmbeddedFile(string fileName)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var stream = assembly.GetManifestResourceStream(fileName);
    
            if (stream == null)
                throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly");
    
            return stream;
        }`