You are on page 1of 13
Database First Article + 10/14/2020 + 6 minutes to read This video and step-by-step walkthrough provide an introduction to Database First development using Entity Framework. Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file. Watch the video This video provides an introduction to Database First development using Entity Framework. Database First allows you to reverse engineer a model from an existing database. The model is stored in an EDMX file (.edmx extension) and can be viewed and edited in the Entity Framework Designer. The classes that you interact with in your application are automatically generated from the EDMX file. Presented By: Rowan Miller Video: WMV | MP4 | WMV (ZIP) Pre-Requisites You will need to have at least Visual Studio 2010 or Visual Studio 2012 installed to complete this walkthrough. If you are using Visual Studio 2010, you will also need to have NuGet _ installed. 1. Create an Existing Database Typically when you are targeting an existing database it will already be created, but for this walkthrough we need to create a database to access. The database server that is installed with Visual Studio is different depending on the version of Visual Studio you have installed: * Ifyou are using Visual Studio 2010 you'll be creating a SQL Express database. * Ifyou are using Visual Studio 2012 then you'll be creating a LocalDB database hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst 43 08/01/2028 23:20 Database Fist - EFS | Microsoft Learn Let's go ahead and generate the database. © Open Visual Studio ‘+ View -> Server Explorer * Right click on Data Connections -> Add Connection... * Ifyou haven't connected to a database from Server Explorer before you'll need to select Microsoft SQL Server as the data source rosoft Access Database Fi Description | Microsoft ODBC Data Source Use this selection to connectto Microsoft SOL Server 2005 or above, Microsoft SQL Server Database File ‘orto Microsoft SQL Azure using the Oracle Database INET Framework Data Provider for SQL Server. Data provider: NET Framework Data Provider for SQL laAlways use this selection * Connect to either LocalDB or SQL Express, depending on which one you have installed, and enter DatabaseFirst.Blogging as the database name hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst ans. (08/01/2028 23:39 Databat Enter information to connect to the selected data source or click “Change” to choose a diferent datz source and/or provider. Date source: Microsoft SQL Server (SqlCiient) Servername: Logon tothe server @ Use Windows Authentication © Use SQL Server Authentication Username Password Save my password Connect to a database @ Select or enter a database name: Datebasefirst. Blogging Attach a database file: fo Logical name! ‘Test Connection hitps:fteam,microsoft.comien-usietfeféimodelin/designerorkiowsidatabase-frst Fst - EF | Microsoft Learn ans. ‘08/01/2028 23:28 Databat Fst - EF | Microsoft Learn Enter information to connect to the selected data source or click “Change” to | choose a different data source and/or provider. Date source: Microsoft SQL Server (SqlCiient) E Logon tothe server @ Use Windows Authentication © Use SQL Server Authentication Username: | reswor [id []Save my password Connect to a database @ Select or enter a database name: Datebasefirst. Blogging . (© Attach a database file: [ ] [_ Bronse..._] Logical name! * Select OK and you will be asked if you want to create a new database, select Yes The dvabsce Blogging’ doesnot eit oryou do rt have pemsion Would you bet attempt tocreatei? ‘+ The new database will now appear in Server Explorer, right-click on it and select New Query * Copy the following SQL into the new query, then right-click on the query and select Execute hitps:te .erosof.comfen-usietet6imodelingdesigneniworkflowsidatabase-frst ans 08/01/2028 23:20 Database Fist - EFS | Microsoft Learn sau CREATE TABLE [dbo]. [Blogs] ( [Blogid] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (200) NULL, [Ur1] NVARCHAR (200) NULL, CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY CLUSTERED ([BlogId] ASC) % CREATE TABLE [dbo]. [Posts] ( [PostId] INT IDENTITY (1, 1) NOT NULL, [Title] NVARCHAR (200) NULL, [Content] NTEXT NULL, [Blogid] INT NOT NULL, CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED ([PostId] ASC), CONSTRAINT [FK_dbo.Posts_dbo.Blogs_Blogld] FOREIGN KEY ([BlogId]) REFERENCES [dbo]. [Blogs] ({Blogid]) ON DELETE CASCADE F 2. Create the Application To keep things simple we're going to build a basic console application that uses the Database First to perform data access: * Open Visual Studio * File -> New -> Project... © Select * Enter DatabaseFirstSample as the name * Select OK indows from the left menu and Console Application 3. Reverse Engineer Model We're going to make use of Entity Framework Designer, which is included as part of Visual Studio, to create our model. * Project -> Add New Item... * Select Data from the left menu and then ADO.NET Entity Data Model * Enter BloggingModel as the name and click OK * This launches the Entity Data Model Wizard © Select Generate from Database and click Next hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst 5113 ‘08/01/2028 23:28 Fst - EB | Microsoft Learn Creates en entity model from a database. Object-layer code 's generated from the model, This opticn aso lets you specify the databare connection, settings for the model, and database cbject te include inthe medel * Select the connection to the database you created in the first section, enter BloggingContext as the name of the connection string and click Next hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst ans, ‘08/01/2028 23:28 Fst - EB | Microsoft Learn Which data connection should your application use to connect te the database? TecslubtB4e26beDetaboscFirsfloggingabo > =) [_ New Connections. Pen Te contain zenstive data {for ample, = password) thatic required te connectto th ring sens in the connect y Fisk De you want te include thi aidan No, exclude sensitive date from the connection sting. Iwill etitin my application cade Jude the sensitive dats inthe connection string Entity connection sting: mtadoanre///BlogsingModecdlres///BleggingMode sl res/"/BloggingModel.mslprovider= System.Data Sa lientprovider connection string="data source= locald)\vi1.0initialcetelog=DetabaseFisi.Blogging/ntegiated -ecurty= True MukiplelictiveReculSete~ True:A\pp-EntityFramework” ‘connection settings in App.Config as * Click the checkbox next to ‘Tables’ to import all tables and click ‘Finish’ hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst 73 08/01/2028 23:20 Database Fist - EFS | Microsoft Learn [Entity Data Model Wizard Bo ewes Which databace objects do you want ta include in your mode? eit Stored Procedures and Functions [| Pluraize or singulerize generated object names Iiclude fersign key colurnne inthe medel Model Nemespace: DatabareFicet BloggingMadel Once the reverse engineer process completes the new model is added to your project and opened up for you to view in the Entity Framework Designer. An App.config file has also been added to your project with the connection details for the database. © Properties 8 Posts File & Content & BlogBiogld Navigation Properties beg Additional Steps in Visual Studio 2010 hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst ans 21012020 23:09 Database Fest- EFS | Microsoft Learn If you are working in Visual Studio 2010 there are some additional steps you need to follow to upgrade to the latest version of Entity Framework. Upgrading is important because it gives you access to an improved API surface, that is much easier to use, as well as the latest bug fixes. First up, we need to get the latest version of Entity Framework from NuGet. * Project -> Manage NuGet Packages... if you don't have the Manage NuGet Packages... option you should install the latest version of NuGet © Select the Online tab © Select the EntityFramework package * Click Install Next, we need to swap our model to generate code that makes use of the DbContext API, which was introduced in later versions of Entity Framework * Right-click on an empty spot of your model in the EF Designer and select Add Code Generation Item... * Select Online Templates from the left menu and search for DbContext © Select the EF 5.x DbContext Generator for C#, enter BloggingModel as the name and click Add es = i sae Crested Bp Mcoson sent Version: 1020 Date Dovwrind #5522 Othe ating: rrr Ye) StarPoit Memes ua So Bterione ‘ied sano Som | “ec By cseesenees set i ccs 4. Reading & Writing Data hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst ons. ‘08/01/2028 23:28 Database Fist - EFS | Microsoft Learn Now that we have a model it's time to use it to access some data. The classes we are going to use to access data are being automatically generated for you based on the EDMx file. This screen shot is from Visual Studio 2012, if you are using Visual Studio 2010 the BloggingModel.tt and BloggingModel.Context.tt files will be directly under your project rather than nested under the EDMX file. @ o-2Qagf oF Search Solution Explorer (Ctrl) P| fal Solution 'DatabaseFirstSemple’ (1 project) 4 [i DatahasefirstSample > & Properties Dem References BD Appiconfig 4-48 BloggingModel.edm 4%) BloggingModel Context > 2) BloggingModel.Designerics 49 BloagingModel edrmdiagram 47) BloggingModeltt 2D packages.config > CF Program.cs Implement the Main method in Program.cs as shown below. This code creates a new instance of our context and then uses it to insert a new Blog. Then it uses a LINQ query to retrieve all Blogs from the database ordered alphabetically by Title. cH class Program { static void Main(string[] args) t using (var db = new BloggingContext()) { // Create and save a new Blog Console.Write("Enter a name for a new Blog: var name = Console.ReadLine(); var blog = new Blog { Name = name }; db.Blogs.Add(blog) db.SaveChanges(); itp !microsof.comien-usiffefeimodelinidesignerorklowsidatabase-frst 1013 (08/01/2028 23:20 Database Fist -EFG | Microsoft Learn // Display all Blogs from the database var query = from b in db.Blogs orderby b.Name select b; Console.WriteLine("All blogs in the database:"); foreach (var item in query) < Console.WriteLine(item.Name) ; } Console.WriteLine("Press any key to exit. Console.ReadKey(); You can now run the application and test it out, Console Enter a name for a new Blog: All blogs in the database: ADO.NET Blog, ADO.NET Blog Press any key to exit. 5. Dealing with Database Changes Now it’s time to make some changes to our database schema, when we make these changes we also need to update our model to reflect those changes The first step is to make some changes to the database schema. We're going to add a Users table to the schema. * Right-click on the Databasefirst.Blogging database in Server Explorer and select New Query * Copy the following SQL into the new query, then right-click on the query and sau. select Execute CREATE TABLE [dbo]. [Users] ¢ [Username] NVARCHAR(S®) NOT NULL PRIMARY KEY, hitps:ftearn microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-frst 03 (08/01/2028 23:20 Database Fist - EFS | Microsoft Learn [DisplayName] NVARCHAR(MAX) NULL Now that the schema is updated, it's time to update the model with those changes. * Right-click on an empty spot of your model in the EF Designer and select ‘Update Model from Database...’ this will launch the Update Wizard ‘* On the Add tab of the Update Wizard check the box next to Tables, this indicates that we want to add any new tables from the schema. The Refresh tab shows any existing tables in the model that will be checked for changes during the update. The Delete tabs show any tables that have been removed from the schema and will also be removed from the model as part of the update. The information on these two tabs is automatically detected and is provided for informational purposes only, you cannot change any settings. 2 we [Elg Stored Proceduras and Functions [Z Plural or singulaize generated object names [Z Include foreign key columnsin the mde! Import selected stored procedures anc functions into the entity model Select items to add to the mode. * Click Finish on the Update Wizard hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst sans. asjova0z3 23:9 Database Fist - EFS | Microsc Lean The model is now updated to include a new User entity that maps to the Users table we added to the database. = Properties © Properties Af Posttd of Username Bite DisplayName # content © Navigation Properties F dlogBlogtd Summary In this walkthrough we looked at Database First development, which allowed us to create a model in the EF Designer based on an existing database. We then used that model to read and write some data from the database. Finally, we updated the model to reflect changes we made to the database schema. hitps:ftearn.microsof.comven-usiffetSimodelingldesigneriworklowsidatabase-fst 133

You might also like