我想在运行时将表添加到 SQLCe 数据库,因为表名不是静态的并且在编译时已知。我尝试使用 Entity Framework 4.1 和 DbContext 执行此操作,如下所示:
public class PersonContext : DbContext
{
public PersonContext()
: base("UnicornsCEDatabase")
{
}
}
public class Person
{
public int NameId { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{
using (var db = new PersonContext())
{
db.Database.Delete();
//Try to create table
DbSet per = db.Set<Person>();
var per1 = new Person { NameId = 1, Name = "James"};
per.Add(per1);
int recordsAffected = db.SaveChanges();
Console.WriteLine(
"Saved {0} entities to the database, press any key to exit.",
recordsAffected);
Console.ReadKey();
}
}
}
尝试运行它时会抛出此错误: 实体类型 Person 不是当前上下文模型的一部分。
是否可以在运行时将 DbSet 添加到 DbContext而无需在数据库中定义该 DbSet(及其模式)?
当使用 Person 静态定义 DbContext 时,EF 将动态创建整个数据库和表,这很棒。
例如:
foreach (var item in collection)
{
string tableName = "PersonTable_"+item.Name;
//Add a table with the name tableName to DbContext
}
这是否可以通过 EF 以某种方式实现,或者我是否必须使用其他技术来创建这些?
谢谢,于尔根