views:

46

answers:

1

I am new to LINQ to SQL, but have done a lot of database development in the past.

The software I just started working on uses:

// MyDataContext is a sub class of DataContext, that is generated with SqlMetal
MyDataContext db = new MyDataContext (connectionString);
db.CreateDatabase();

to create the database when it is first run.

I need to add some indexes to the tables....
How can I tell the DataContext what indexes I want?

Otherwise how do I control this?

(I could use a sql script, but I like the ideal that db.CreateDatabase will always create a database that matches the data access code)

(For better, or worse the software has full access to the database server and our software often create databases on the fly to store result of model runs etc, so please don’t tell me we should not be creating databases from code)


I seem not to be the only person hitting limts on DataContext.CreateDatabase() see also http://csainty.blogspot.com/2008/02/linq-to-sql-be-careful-of.html

+1  A: 

As far as I know the DataContext.CreateDatabase method can only create primary keys.

When you look at the DBML directly, you will see that there are no elements for defining an index. Therefore it is, IMHO, save to assume that CreateDatabase cannot do it.

So the only way I can think of for creating indexes "automatically" is by first calling DataContext.CreateDatabase and then calling DataContext.ExecuteCommand to add the indexes to the tables that were just created.

Obalix
Thanks, I have come to the same conclusion, but the problem I am having is I don’t want the primary key to be a clustered index, as I have a DateTime column that a lot of range queries are done on.
Ian Ringrose
One always have to keep in mind that Linq to SQL is more of a convenience tool. It is easy to use but it does not provide the complete flexibility of a "propper" ORM. We will have to wait for the things hitting us with .NET 4.0 and the Entity Framework - hopefully it is usable by then. Here a link to the changes in Linq (nice pun there) in .NET 4.0 http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40.
Obalix