从EF Code-First DbContext类生成SQL CE数据库 [英] Generate SQL CE database from EF Code-First DbContext class
问题描述
我已经在Entity Framework Code-First约定的样式中定义了一组类,并用System.ComponentModel.DataAnnotations属性注释了类属性。
I've defined a set of classes in the style of Entity Framework Code-First conventions and annotated the class properties with System.ComponentModel.DataAnnotations attributes.
现在我想从此代码生成SQL Server Compact Edition(SCSE)(4.0)数据库。
Now I want to generate a SQL Server Compact Edition (SCSE) (4.0) database from this code.
需要什么代码来执行此操作以及需要导入哪些程序集?
What code is needed to do this and what assemblies need to be imported?
到目前为止,我已导入C:\Program文件(x86)\Microsoft SQL Server Compact Edition \v4.0 \Desktop {System.Data .SqlServerCe.dll,System.Data.SqlServerCe.Entity\System.Data.SqlServerCe.Entity.dll} dll文件。
So far I've imported the 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 files.
任何指针都赞赏。
推荐答案
我找到了解决方案。关键的是这行代码:
I found the solution. The critical thing is this line of code:
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虽然,但这是现在如何做。
The API will probably change between EF Code-First CTP 5 and RTM though, but this is how it's done now.
我做了一个小的 blog post 关于它。
I've made a small blog post about it.
这篇关于从EF Code-First DbContext类生成SQL CE数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!