Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening an SQL CE file at runtime with Entity Framework 4

I am getting started with Entity Framework 4, and I an creating a demo app as a learning exercise. The app is a simple documentation builder, and it uses a SQL CE store. Each documentation project has its own SQL CE data file, and the user opens one of these files to work on a project.

The EDM is very simple. A documentation project is comprised of a list of subjects, each of which has a title, a description, and zero or more notes. So, my entities are Subject, which contains Title and Text properties, and Note, which has Title and Text properties. There is a one-to-many association from Subject to Note.

I am trying to figure out how to open an SQL CE data file. A data file must match the schema of the SQL CE database created by EF4's Create Database Wizard, and I will implement a New File use case elsewhere in the app to implement that requirement. Right now, I am just trying to get an existing data file open in the app.

I have reproduced my existing 'Open File' code below. I have set it up as a static service class called File Services. The code isn't working quite yet, but there is enough to show what I am trying to do. I am trying to hold the ObjectContext open for entity object updates, disposing it when the file is closed.

So, here is my question: Am I on the right track? What do I need to change to make this code work with EF4? Is there an example of how to do this properly?

Thanks for your help.

My existing code:

public static class FileServices
{
    #region Private Fields

    // Member variables
    private static EntityConnection m_EntityConnection;
    private static ObjectContext m_ObjectContext;

    #endregion

    #region Service Methods

    /// <summary>
    /// Opens an SQL CE database file.
    /// </summary>
    /// <param name="filePath">The path to the SQL CE file to open.</param>
    /// <param name="viewModel">The main window view model.</param>
    public static void OpenSqlCeFile(string filePath, MainWindowViewModel viewModel)
    {  
        // Configure an SQL CE connection string
        var sqlCeConnectionString = string.Format("Data Source={0}", filePath);

        // Configure an EDM connection string
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = "res://*/EF4Model.csdl|res://*/EF4Model.ssdl|res://*/EF4Model.msl";
        builder.Provider = "System.Data.SqlServerCe";
        builder.ProviderConnectionString = sqlCeConnectionString;
        var entityConnectionString = builder.ToString();

        // Connect to the model
        m_EntityConnection = new EntityConnection(entityConnectionString);
        m_EntityConnection.Open();

        // Create an object context
        m_ObjectContext = new Model1Container();

        // Get all Subject data
        IQueryable<Subject> subjects = from s in Subjects orderby s.Title select s;

        // Set view model data property
        viewModel.Subjects = new ObservableCollection<Subject>(subjects);
    }

    /// <summary>
    /// Closes an SQL CE database file.
    /// </summary>
    public static void CloseSqlCeFile()
    {
        m_EntityConnection.Close();
        m_ObjectContext.Dispose();
    }

    #endregion
}
like image 533
David Veeneman Avatar asked Jan 24 '26 04:01

David Veeneman


1 Answers

Here is the answer. I simplified my code and ran it on simpler EDM model, Disney Characters. Model has two entities, Character and Child, with a 1:* association between Character and Child. Children are character's kids--pretty simple stuff. I wrote the demo as a console app to keep it as simple as possible.

Complete code in Program.cs is as follows:

class Program
{
    static void Main(string[] args)
    {
        /* See http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/8a89a728-6c8d-4734-98cb-11b196ba11fd */

        // Configure an SQL CE connection string 
        var filePath = @"D:\Users\dcveeneman\Documents\Visual Studio 2010\Demos\SqlCeEf4Demo\SqlCeEf4Demo\DisneyChars.sdf";
        var sqlCeConnectionString = string.Format("Data Source={0}", filePath);

        // Create an EDM connection
        var builder = new EntityConnectionStringBuilder();
        builder.Metadata = "res://*/DisneyChars.csdl|res://*/DisneyChars.ssdl|res://*/DisneyChars.msl";
        builder.Provider = "System.Data.SqlServerCe.3.5";
        builder.ProviderConnectionString = sqlCeConnectionString;
        var edmConnectionString = builder.ToString();
        var edmConnection = new EntityConnection(edmConnectionString);

        // Build and query an ObjectContext
        using (var context = new DisneyCharsContainer(edmConnection))
        {
            var chars = context.Characters;
            foreach(var character in chars)
            {
                Console.WriteLine("Character name: {0}", character.Name);
                foreach(var child in character.Children)
                {
                    Console.WriteLine("Child name: {0}", child.Name);
                }
            }
            Console.ReadLine();
        }
    }
}

Link at the top of the code is to a forum thread that I used to write the code.

Here is the walkthrough: First, create a database connection. Since I am using SQL CE, I don't have a connection string builder--the connection string is simply a path, so I don't need one. Then I use an EntityConnectionStringBuilder to build an entity connection string, and then I use that to build an EntityConnection. Finally, I pass the connection to the constructor for my ObjectContext. I can then use the ObjectContext to query the EDM.

like image 65
David Veeneman Avatar answered Jan 26 '26 18:01

David Veeneman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!