Search code examples
entity-frameworkef-code-firstsql-server-celinqpad

LinqPad + EF 4.1 + SQL Server CE


I've been toying with the idea for a couple of days, but I can't find any definitive evidence to suggest this will or will not work.

What I want to do is use LinqPad queries to create a EF 4.1 code-first database with a SQL Server CE backing in the same directory as the query (possibly named the same as the query). The reason for this would be to quickly set up a database for storing query results for further processing.

The idea is to store the class definitions in the query, i.e. (These will work with the latest beta

public class User
{
    public long Id { get; set; }
    public string Name{ get; set; }
}

public class MyDBContext : DbContext
{
    // note the overloaded constructor
    // just pass in the LinqPad UserQuery connection
    public MyDBContext(DbConnection connection) : base(connection, true)
    {}
    public DbSet<User> Users { get; set; }
}

Then in the query:

#define NONEST
public Main()
{
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyDBContext>());
    // pass in the current database connection to point EF to the right database
    var context = new MyDBContext(this.Connection);
    context.Users.Add(new User(){Name = "Test User"});
    context.SaveChanges();

    context.Users.Dump("Contents of Users table");
}

I've referenced EntityFramework 4.2.0.0 in LinqPad, but in my query, I can't see the System.Data.Entity namespace. Is this indicative of some other problem?

I'm not sure if I've given enough context or information, so let me know if you need clarification. Can this be done? Does LinqPad not support this yet?

Update:

It appears that EF can't map nested classes, which is exactly what LinqPad query defined classes are. I'm not very experienced in this context, but it seems that I've hit a dead end. Unless Joe Albahari can somehow get non-nested user classes implemented, it doesn't look like this will work. Anyone have ideas?

Final Update:

Using the latest beta, this completely works. It requires creating the .sdf database file beforehand, but all other operations should work. Very cool. Thanks Joe Albahari!


Solution

  • Download the latest beta and then add the following directive to the start of your query:

    #define NONEST
    

    This will tell LINQPad to move types that you define a level up, so that they're non-nested.