是否可以将数据库首先和代码优先模型与实体框架进行混合? [英] Is it possible to mix database first and code first models with entity framework?

查看:146
本文介绍了是否可以将数据库首先和代码优先模型与实体框架进行混合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我即将开始一个Web应用程序,在此我想使用实体框架(主要是)代码第一个模型。

I am about to begin a web application where I would like to use the entity framework with (mostly) code first models.

但是,除了应用程序我打算创建的特定模型,我必须使用外部用户数据库。可以将我的一个模型指定为数据库,并使用单独的数据库上下文吗?

However, in addition to the application-specific models I plan to create, I have to use an external user database. Is it possible to specify one of my models as database first and to use a separate database context?

推荐答案

从技术上讲,但我不会推荐它。最好只是全面使用代码优先。是的,讽刺的是,您可以使用现有数据库的代码优先。

Technically, it's possible, but I wouldn't recommend it. It's far better to just use code-first across the board. Yes, ironically, you can use "code-first" with an existing database.

只需创建与现有数据库中的表匹配的POCO。如果您的POCO没有与您的表命名相同(并不是所有的表名称都是有效或适当的类名),您可以使用 Table 属性来明确告诉EF什么表您的POCO适用于:

Just create POCOs that match the tables in your existing database. If your POCO is not named the same as your table (not all table names would be valid or appropriate class names), you can use the Table attribute to explicitly tell EF what table your POCO works with:

[Table("SomeTable")]
public class MyAwesomeEntity
{
    ...
}

然后,你需要一个单独的上下文对于此现有数据库和属于它的任何实体。所有你需要做的是1)告诉它应该使用什么连接字符串,2)关闭数据库初始化,所以EF不会试图实际创建数据库。

Then, you'll need a separate context specifically for this existing database and any entities that belong to it. All you have to do is 1) tell it what connection string it should use and 2) turn off database initialization, so EF doesn't try to actually create the database.

public MyExistingDatabaseContext : DbContext
{
    public MyExistingDatabaseContext()
        : base("MyExistingDatabaseConnectionStringName")
    {
        Database.SetInitializer<MyExistingDatabaseContext>(null);
    }

    // DbSets here
}

就是这样。每当您需要使用现有数据库中的实体进行处理时,只需新建一个上下文,或者通过一个DI(依赖关系注入)容器,或者通过一个DI(依赖注入)容器来获取它)。

And that's it. Whenever you need to work with an entity from this existing database, just new up this context or get it some other way, such as through a DI (dependency injection) container, and go to town.

这篇关于是否可以将数据库首先和代码优先模型与实体框架进行混合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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