2011-01-29 118 views
13

我已经定义了一组类,其风格为实体框架Code-First约定,并使用System.ComponentModel.DataAnnotations属性注释了类属性。从EF代码生成SQL CE数据库 - 第一个DbContext类

现在我想从这段代码中生成一个SQL Server Compact Edition(SCSE)(4.0)数据库。

需要什么代码才能做到这一点,以及需要导入哪些程序集?到目前为止,我已经导入了C:\ Program Files(x86)\ Microsoft SQL Server Compact Edition \ v4.0 \ Desktop {System.Data.SqlServerCe.dll,System.Data.SqlServerCe.Entity \ System。 Data.SqlServerCe.Entity.dll} dll文件。

任何指针赞赏。文章和whatnot。

回答

15

我找到了解决方案。关键的是这行代码:

DbDatabase.DefaultConnectionFactory = new 
         SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); 

这里有一个完整的示例:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Proto 
{ 
    using System.Data; 
    using System.Data.Entity; 
    using System.Data.Entity.Database; 
    using System.Data.SqlServerCe; 
    using System.ComponentModel.DataAnnotations; 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      DbDatabase.DefaultConnectionFactory = new 
         SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); 
      DbDatabase.SetInitializer(
         new DropCreateDatabaseIfModelChanges<ProtoCatalog>() 
       ); 

      using (var db = new ProtoCatalog()) 
      { 
       var user = new User 
       { 
        Name = "bob", 
        Password = "123", 
        Creation = DateTime.Now, 
        PrimaryEmailAddress = "[email protected]" 
       }; 

       db.Users.Add(user); 

       db.SaveChanges(); 

       Console.ReadKey(); 
      } 
     } 
    } 

    public class ProtoCatalog : DbContext 
    { 
     public DbSet<User> Users { get; set; } 
    } 

    public class User 
    { 
     [Key, StringLength(50)] 
     public string Name { get; set; } 

     [Required, StringLength(100)] 
     public string Password { get; set; } 

     [Required, StringLength(320)] 
     public string PrimaryEmailAddress { get; set; } 

     [StringLength(320)] 
     public string SecondaryEmailAddress { get; set; } 

     [Required] 
     public DateTime Creation { get; set; } 

     public bool Active { get; set; } 
    } 
} 

的API可能会EF代码优先CTP 5和RTM之间改变虽然,但这是它是如何做现在。

我对此做了一个小的blog post

2

我发现,最好的办法是安装的NuGet,并与EF CodeFirst和SQL CE 4包玩,也有您可以从NuGet中安装示例,其中包含所有数据库创建策略的代码示例。 你会做这样的事情:

install-package EFCodeFirst.SqlServerCompact 
install-package EFCodeFirst.Sample 

在项目目录的根目录应该是一个名为“AppStart_SQLCEEntityFramework.cs”是指为实例文件。

+0

谢谢!我只是在家里安装了Visual C#Express,但这可能会改变。 – 2011-01-30 13:49:07

2

提供DefaultConnectionProvider的另一种方法是将其添加到app.config中。

<entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework"> 
    <parameters> 
     <parameter value="System.Data.SqlServerCe.4.0" /> 
    </parameters> 
    </defaultConnectionFactory> 
</entityFramework>