Please I have a question and I have searched extensively on Google but couldn't get concrete answers.
I have a project. I already used the Identity framework and by this, it generated the database using code first.
I intend to use database-first for subsequent tables.
My questions are below:
Can I generate the database first such that it uses same DbContext
as the code first entities?
Will they have separate connection strings?
Do I have to continue using code-first, or can the two approaches be combined in a project?
I am actually new to Entity Framework.
Thanks
- Can I generate the database first such that it uses same
DbContext
as the code first entities?
No you can't, assuming you're using ADO.NET Entity Data Model
/ .edmx
to import your database tables you generated into your project.
The reason is, when you use Code First
, your connection string in the web.config
will look something like the following:
<connectionStrings>
<add name="YOUR_IDENTITY_CONTEXT_NAME" providerName="System.Data.SqlClient"
connectionString="Data Source=xxx; Initial Catalog=xxx; User Id=xxx; Password=xxx;" />
</connectionStrings>
But when you use .edmx
to import tables into models/classes into your project, it won't see your existing connection string you had with Code First
. Instead, you will have to create a new connection string, which will look like the following:
<connectionStrings>
<add name="YOUR_DATABASE_FIRST_CONTEXT_NAME" providerName="System.Data.EntityClient"
connectionString="metadata=res://*/xxx|res://*/xxx|res://*/xxx;provider=System...." />
</connectionStrings>
- Will they have separate connection strings?
Yes, they will.
- Do I have to continue using code-first, or can the two approaches be combined in a project?
It would be great if you can use Code First
all the way through, but if you can't, there are other ways you can mix Code First
and Database First
approach:
Just use 2 separate connection strings
I typically name the Identity DbContext AppIdentityDbContext
, while the data context generated by .edmx
just AppDbContext
.
Use different ORMs other than Entity Framework
You don't have to stick with one ORM in a project. You can use Entity Framework
for identity stuff, and use something else, such as Dapper, for reading.