我以实体框架代码优先约定的方式定义了一组类,并用System.ComponentModel.DataAnnotations属性注释了类属性。
现在,我想从这段代码生成一个SQL Server Compact Edition (SCSE) (4.0)数据库。
执行此操作需要哪些代码,需要导入哪些程序集?
到目前为止,我已经导入了C:\Program files (x86)\Microsoft SQL Server Compact dll dll文件。
感谢您的指点。文章之类的。
发布于 2011-01-31 13:06:31
我找到了解决方案。关键的是这一行代码:
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之间进行更改,但这就是现在的方式。
我做了一个关于它的小blog post。
发布于 2011-01-30 18:01:47
请参阅此博客和同一篇文章中的链接(例如ScottGu文章):http://erikej.blogspot.com/2011/01/sql-server-compact-40-released.html
发布于 2011-01-30 18:21:51
我找到的最好的方法是安装NuGet并使用EF CodeFirst和SQLCE4包,还有一个可以从NuGet安装的示例,其中包含所有数据库创建策略的代码示例。你可以这样做:
install-package EFCodeFirst.SqlServerCompact
install-package EFCodeFirst.Sample在项目目录的根目录中应该有一个名为"AppStart_SQLCEEntityFramework.cs“的文件,有关示例,请参阅该文件。
https://stackoverflow.com/questions/4838217
复制相似问题