C#EF 4.1在DbContext中动态创建表 [英] C# EF 4.1 Create table dynamically within DbContext

查看:741
本文介绍了C#EF 4.1在DbContext中动态创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时将表添加到SQLCe数据库,因为表名不是静态的,并且在编译时是已知的。
我尝试使用Entity Framework 4.1和DbContext做到这一点,如下所示:

I want to add tables to a SQLCe database at runtime, since the tablenames are not static and known at compile time. I try to do this with Entity Framework 4.1 and DbContext as follows:

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不是当前上下文模型的一部分

When trying to run this it throws this error: The entity type Person is not part of the model for the current context.

是否可以添加在运行时将DbSet设置为DbContext 而不必在数据库中定义该DbSet(及其模式)?

Is it possible to add a DbSet at runtime to the DbContext without having to define that DbSet(with its schema) in the database?

当静态定义DbContext时,亲爱的,EF会快速创建整个数据库和表。

When defining the DbContext statically with Person, EF will create the entire database and the tables on the fly, which is great.

例如:

foreach (var item in collection)
{
   string tableName = "PersonTable_"+item.Name;
   //Add a table with the name tableName to DbContext
}

感谢Juergen

推荐答案

您可以使用以下命令,它将创建表或根据需要对其进行更新,不确定是否可以在生产中使用,因为当模型更改时它将删除db

you could use following, it would create tables or update them as necessary, not sure if this would work in production since it drops the db when model changes

 Database.SetInitializer<DataContext>(
                new DropCreateDatabaseIfModelChanges<DataContext>());

或者是否可以创建自己的System.Data.Entity.IDatabaseInitializer接口实现

or if could create your own implementation of System.Data.Entity.IDatabaseInitializer interface

这篇关于C#EF 4.1在DbContext中动态创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆