Opening an SQL CE file at runtime with Entity Framework 4

前端 未结 2 551
悲&欢浪女
悲&欢浪女 2021-01-06 18:59

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. Eac

2条回答
  •  逝去的感伤
    2021-01-06 19:36

    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.

提交回复
热议问题