Dynamically Create a Database (LINQ to SQL) from edmx or dbml - Export DBML to SQL script

1543
Views
1
Answers

I lost my SQL server database of a application I was working on but I still have my DBML files I used in my .NET project.

Is it possible to export my DBML/EDMX somehow to a SQL server create script, to recreate my databases in SQL server.

edit | flag
William Patrick
Asked on: Dec 14, 2011 at 10:15PM

1 Answers

90
4
90

Yes certainly you can..
In LINQ to SQL, an object model is mapped to a relational database. Mapping is enabled by using attribute-based mapping or an external mapping file to describe the structure of the relational database. In both scenarios, there is enough information about the relational database that you can create a new instance of the database using the

DataContext.CreateDatabase method.

Follow these steps to recreate the database.

public void CreateDatabase()
{
   
MyDatabase db = new MyDatabase ("c:\\MyDatabase.mdf");
    db
.CreateDatabase();
}

If the database already exists and drop it before creating a new one. The DataContext class provides the DatabaseExists and DeleteDatabase methods to help you with this process.

The following example shows how to implement this approach:

public void CreateDatabase2()
{
   
MyDatabase db = new MyDatabase (@"c:\MyDatabase.mdf");
   
if (db.DatabaseExists())
   
{
       
Console.WriteLine("Deleting old database...");
        db
.DeleteDatabase();
   
}
    db
.CreateDatabase();
}

or you can point the mdf location into SQL Server folder as

C:\SQL2008\DATA\MyDatabase.mdf

Cheers!!!

edit | flag
Gokul A
Answered on: Dec 14, 2011 at 10:23PM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags