SQL Metal for specific tables or another way to re

2019-04-09 13:00发布

问题:

anybody have any easy way of doing this in Visual Studio, without having to use the Server Explorer ?

I tried also looking at macro's but recording only produce

  Sub TemporaryMacro()
  End Sub

So no luck there.

Any way to script this?

回答1:

SqlMetal Include worked like a charm for me. First Create a complete dbml file using SqlMeta - Say testComplete.dbml

Now provide this file as an input to SqlMetaInclude SqlMetalInclude /dbml:"testComplete.dbml" /output:"testSubSet.dbml" /include:dbo.SampleTable1=SampleTable1,dbo.SampleTable2=SampleTable2

Note that this tool in has a GUI included which can handle the complete process.



回答2:

I am using a batch script similar to this to manage the updating of my models when the underlying tables/views change. To use it:

  1. Have SQLMetal and SQLMetalInclude (you may have to download and build from source) accessible from the current directory (or in the path)
  2. Create a file "chosenEntities.txt" with a table/view name on each line. These tables will be the only ones that code is generated for.
  3. Modify, save and execute the Generate.bat batch code
  4. (Optional) Add the .bat file as an external run tool to Visual Studio, as explained here

Generate.bat:

sqlmetal /conn:"Data Source={Hostname};Initial Catalog={DBName};User ID={Username};Password={Password}" /dbml:temp.dbml /views

setlocal EnableDelayedExpansion
set file=chosenEntities.txt
set include=
FOR /F %%i IN (%file%) DO (
set include=!include!%%i,
)
set include=%include:~0,-1%

sqlmetalinclude -dbml:temp.dbml -output:ChosenEntities.dbml -include:%include%

sqlmetal /context:CustomDataContext /pluralize /namespace:MyNamespace.DB /language:csharp /code:DBEntities.cs /entitybase:DBEntityBase ChosenEntities.dbml

chosenEntities.txt example:

Accounts
Customers
PRODUCTS_VIEW
AnotherTable

Explanation:

  1. Intermediate .dbml file is generated by sqlmetal as usual. The created dbml file contains the definitions for every single table in the database (and views, if selected)
  2. The next code block loops through chosenEntities.txt, and for each line appends the line contents (table name) plus a comma ','
  3. The last trailing comma is removed
  4. Run sqlmetalinclude, which basically makes a copy of the original temp.dbml file, but only including the Tables you specified. There are other options available, like transforming the individual table names
  5. sqlmetal is run a second time, this time generating the actual .cs code based on the cut-down .dbml file.


回答3:

There is one good utility out there which helps you update your existing DBML files from the database: Huagati DBML/EDMX tools.

It's not free, but worth the investment for any serious Linq-to-SQL development.

The only alternative would be to write it yourself - read the database structure and compare that to the XML representation in the DBML, and update the DBML as needed.