Dot-Net

從 EF Code-First DbContext 類生成 SQL CE 數據庫

  • August 23, 2012

我以實體框架程式碼優先約定的風格定義了一組類,並使用 System.ComponentModel.DataAnnotations 屬性對類屬性進行了註釋。

現在我想從此程式碼生成一個 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 文件。

任何指針表示讚賞。文章什麼的。

我找到了解決方案。關鍵是這行程式碼:

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 = "bob@example.com"
               };

               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 Code-First CTP 5 和 RTM 之間發生變化,但這就是現在的做法。

我已經寫了一篇關於它的小部落格文章

引用自:https://stackoverflow.com/questions/4838217