简体   繁体   English

是否可以将数据库优先模型和代码优先模型与实体框架混合使用?

[英]Is it possible to mix database first and code first models with entity framework?

I am about to begin a web application where I would like to use the Entity Framework with (mostly) code first models. 我将要开始一个Web应用程序,在该应用程序中我想将Entity Framework与(主要是)代码优先模型一起使用。

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. 是的,具有讽刺意味的是,您可以对现有数据库使用“代码优先”。

Just create POCOs that match the tables in your existing database. 只需创建与现有数据库中的表匹配的POCO。 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: 如果您的POCO的名称与表的名称不同(并非所有表名都是有效的或适当的类名),则可以使用Table属性明确告诉EF您的POCO使用的Table

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

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. 您要做的就是1)告诉它应该使用哪个连接字符串,以及2)关闭数据库初始化,因此EF不会尝试实际创建数据库。

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

    // DbSets here
}

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. 每当您需要使用该现有数据库中的实体时,只需更新此上下文或以其他方式获取它(例如通过DI(依赖项注入)容器),然后就可以使用。

You should use the code first from database option if you already have an existing database available but want to use code first. 如果您已经有一个可用的数据库,但想先使用代码,则应该先从数据库中选择代码。

1) In your Models folder, right click on Add, New item, 1)在“模型”文件夹中,右键单击“添加”,“新项目”,

2) Select ADO.NET Entity Data Model in the Data tab. 2)在“数据”选项卡中选择“ ADO.NET实体数据模型”。

3) Enter a model name, 3)输入型号名称,

4) Select Code First from database. 4)从数据库中选择Code First。

5) Select connection string, 5)选择连接字符串,

6) Choose your database objects you want to include in your model. 6)选择要包含在模型中的数据库对象。

You don't have to write the code for the context and model from scratch because it will generate the classes for you. 您不必从头开始编写上下文和模型的代码,因为它将为您生成类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM