Entity Framework Auto Generate Key
How can I get Id of inserted entity in Entity framework? Get Record ID in Entity Framework after insert; Answer. It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to the contexct and call SaveChanges on that context. Id will be automatically filled for you. The Microsoft Entity Framework is an Object Relational Mapping (O/RM) tool that enables you to generate a data access layer from a database automatically. The Entity Framework enables you to avoid the tedious work of building your data access classes by hand. Aug 20, 2012 I have designed a database in Entity Framework 4.1 with Visual Studio 2010 - when the SQL is generated every single foreign key in every table is duplicated. In other words, duplicate columns are generated in the tables. I also noticed that these duplicate foreign key columns are used throughout every association in the EDMX. How the value is generated for added entities will depend on the database provider being used. Database providers may automatically setup value generation for some property types, but others may require you to manually setup how the value is generated. Sep 14, 2016 Entity Framework Core supports different key generation strategies like identity, Sequence and HiLo. In my previous post, I talked about using SQL Server Sequence with EF Core to Create Primary Key. Database sequences are cached, scalable. The Entity Framework Core Fluent API ValueGeneratedOnAdd method indicates that the value for the selected property is generated by the database whenever a new entity is added to the database. Therefore, the property should be ignored by EF Core when constructing an INSERT statement. When you start learning Entity Framework, you will also often see the term Entity Framework Database First. Database first is one of the three approaches to create an entity model. In the Entity Framework, the Database First Approach provides an alternative to the Code First by creating POCO classes from the existing database.
-->by Microsoft
In this tutorial, you learn how to use ASP.NET MVC with the Microsoft Entity Framework. You learn how to use the Entity Wizard to create an ADO.NET Entity Data Model. Over the course of this tutorial, we build a web application that illustrates how to select, insert, update, and delete database data by using the Entity Framework.
The goal of this tutorial is to explain how you can create data access classes using the Microsoft Entity Framework when building an ASP.NET MVC application. This tutorial assumes no previous knowledge of the Microsoft Entity Framework. By the end of this tutorial, you'll understand how to use the Entity Framework to select, insert, update, and delete database records.
The Microsoft Entity Framework is an Object Relational Mapping (O/RM) tool that enables you to generate a data access layer from a database automatically. The Entity Framework enables you to avoid the tedious work of building your data access classes by hand.
In order to illustrate how you can use the Microsoft Entity Framework with ASP.NET MVC, we'll build a simple sample application. We'll create a Movie Database application that enables you to display and edit movie database records.
This tutorial assumes that you have Visual Studio 2008 or Visual Web Developer 2008 with Service Pack 1. You need Service Pack 1 in order to use the Entity Framework. You can download Visual Studio 2008 Service Pack 1 or Visual Web Developer with Service Pack 1 from the following address:
Note
There is no essential connection between ASP.NET MVC and the Microsoft Entity Framework. There are several alternatives to the Entity Framework that you can use with ASP.NET MVC. For example, you can build your MVC Model classes using other O/RM tools such as Microsoft LINQ to SQL, NHibernate, or SubSonic.
Creating the Movie Sample Database
The Movie Database application uses a database table named Movies that contains the following columns:
Column Name | Data Type | Allow Nulls? | Is Primary Key? |
---|---|---|---|
Id | int | False | True |
Title | nvarchar(100) | False | False |
Director | nvarchar(100) | False | False |
You can add this table to an ASP.NET MVC project by following these steps:
- Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
- From the Add New Item dialog box, select SQL Server Database, give the database the name MoviesDB.mdf, and click the Add button.
- Double-click the MoviesDB.mdf file to open the Server Explorer/Database Explorer window.
- Expand the MoviesDB.mdf database connection, right-click the Tables folder, and select the menu option Add New Table.
- In the Table Designer, add the Id, Title, and Director columns.
- Click the Save button (it has the icon of the floppy) to save the new table with the name Movies.
After you create the Movies database table, you should add some sample data to the table. Right-click the Movies table and select the menu option Show Table Data. You can enter fake movie data into the grid that appears.
Creating the ADO.NET Entity Data Model
In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.
Follow these steps:
- Right-click the Models folder in the Solution Explorer window and select the menu option Add, New Item.
- In the Add New Item dialog, select the Data category (see Figure 1).
- Select the ADO.NET Entity Data Model template, give the Entity Data Model the name MoviesDBModel.edmx, and click the Add button. Clicking the Add button launches the Data Model Wizard.
- In the Choose Model Contents step, choose the Generate from a database option and click the Next button (see Figure 2).
- In the Choose Your Data Connection step, select the MoviesDB.mdf database connection, enter the entities connection settings name MoviesDBEntities, and click the Next button (see Figure 3).
- In the Choose Your Database Objects step, select the Movie database table and click the Finish button (see Figure 4).
After you complete these steps, the ADO.NET Entity Data Model Designer (Entity Designer) opens.
Figure 1 – Creating a new Entity Data Model
Figure 2 – Choose Model Contents Step
Figure 3 – Choose Your Data Connection
Figure 4 – Choose Your Database Objects
Modifying the ADO.NET Entity Data Model
After you create an Entity Data Model, you can modify the model by taking advantage of the Entity Designer (see Figure 5). You can open the Entity Designer at any time by double-clicking the MoviesDBModel.edmx file contained in the Models folder within the Solution Explorer window.
Figure 5 – The ADO.NET Entity Data Model Designer
For example, you can use the Entity Designer to change the names of the classes that the Entity Model Data Wizard generates. The Wizard created a new data access class named Movies. In other words, the Wizard gave the class the very same name as the database table. Because we will use this class to represent a particular Movie instance, we should rename the class from Movies to Movie.
If you want to rename an entity class, you can double-click on the class name in the Entity Designer and enter a new name (see Figure 6). Alternatively, you can change the name of an entity in the Properties window after selecting an entity in the Entity Designer.
Figure 6 – Changing an entity name
Remember to save your Entity Data Model after making a modification by clicking the Save button (the icon of the floppy disk). Behind the scenes, the Entity Designer generates a set of C# classes. You can view these classes by opening the MoviesDBModel.Designer.cs file from the Solution Explorer window.
Don't modify the code in the Designer.cs file since your changes will be overwritten the next time you use the Entity Designer. If you want to extend the functionality of the entity classes defined in the Designer.cs file then you can create partial classes in separate files.
Selecting Database Records with the Entity Framework
Let's start building our Movie Database application by creating a page that displays a list of movie records. The Home controller in Listing 1 exposes an action named Index(). The Index() action returns all of the movie records from the Movie database table by taking advantage of the Entity Framework.
Listing 1 – ControllersHomeController.cs
Notice that the controller in Listing 1 includes a constructor. The constructor initializes a class-level field named _db. The _db field represents the database entities generated by the Microsoft Entity Framework. The _db field is an instance of the MoviesDBEntities class that was generated by the Entity Designer.
In order to use theMoviesDBEntities class in the Home controller, you must import the MovieEntityApp.Models namespace (MVCProjectName.Models).
The _db field is used within the Index() action to retrieve the records from the Movies database table. The expression _db.MovieSet represents all of the records from the Movies database table. The ToList() method is used to convert the set of movies into a generic collection of Movie objects (List<Movie>).
The movie records are retrieved with the help of LINQ to Entities. The Index() action in Listing 1 uses LINQ method syntax to retrieve the set of database records. If you prefer, you can use LINQ query syntax instead. The following two statements do the very same thing:
Use whichever LINQ syntax – method syntax or query syntax – that you find most intuitive. There is no difference in performance between the two approaches – the only difference is style.
The view in Listing 2 is used to display the movie records.
Listing 2 – ViewsHomeIndex.aspx
The view in Listing 2 contains a foreach loop that iterates through each movie record and displays the values of the movie record's Title and Director properties. Notice that an Edit and Delete link is displayed next to each record. Furthermore, an Add Movie link appears at the bottom of the view (see Figure 7).
Figure 7 – The Index view
The Index view is a typed view. The Index view includes a <%@ Page %> directive with an Inherits attribute that casts the Model property to a strongly typed generic List collection of Movie objects (List<Movie).
Inserting Database Records with the Entity Framework
You can use the Entity Framework to make it easy to insert new records into a database table. Listing 3 contains two new actions added to the Home controller class that you can use to insert new records into the Movie database table.
Listing 3 – ControllersHomeController.cs (Add methods)
The first Add() action simply returns a view. The view contains a form for adding a new movie database record (see Figure 8). When you submit the form, the second Add() action is invoked.
Notice that the second Add() action is decorated with the AcceptVerbs attribute. This action can be invoked only when performing an HTTP POST operation. In other words, this action can only be invoked when posting an HTML form.
The second Add() action creates a new instance of the Entity Framework Movie class with the help of the ASP.NET MVC TryUpdateModel() method. The TryUpdateModel() method takes the fields in the FormCollection passed to the Add() method and assigns the values of these HTML form fields to the Movie class.
When using the Entity Framework, you must supply a 'white list' of properties when using the TryUpdateModel or UpdateModel methods to update the properties of an entity class.
Next, the Add() action performs some simple form validation. The action verifies that both the Title and Director properties have values. If there is a validation error, then a validation error message is added to ModelState.
If there are no validation errors then a new movie record is added to the Movies database table with the help of the Entity Framework. The new record is added to the database with the following two lines of code:
The first line of code adds the new Movie entity to the set of movies being tracked by the Entity Framework. The second line of code saves whatever changes have been made to the Movies being tracked back to the underlying database.
Figure 8 – The Add view
Updating Database Records with the Entity Framework
You can follow almost the same approach to edit a database record with the Entity Framework as the approach that we just followed to insert a new database record. Listing 4 contains two new controller actions named Edit(). The first Edit() action returns an HTML form for editing a movie record. The second Edit() action attempts to update the database.
Listing 4 – ControllersHomeController.cs (Edit methods)
The second Edit() action starts by retrieving the Movie record from the database that matches the Id of the movie being edited. The following LINQ to Entities statement grabs the first database record that matches a particular Id:
Next, the TryUpdateModel() method is used to assign the values of the HTML form fields to the properties of the movie entity. Notice that a white list is supplied to specify the exact properties to update.
Next, some simple validation is performed to verify that both the Movie Title and Director properties have values. If either property is missing a value, then a validation error message is added to ModelState and ModelState.IsValid returns the value false.
Finally, if there are no validation errors, then the underlying Movies database table is updated with any changes by calling the SaveChanges() method.
When editing database records, you need to pass the Id of the record being edited to the controller action that performs the database update. Otherwise, the controller action will not know which record to update in the underlying database. The Edit view, contained in Listing 5, includes a hidden form field that represents the Id of the database record being edited.
Listing 5 – ViewsHomeEdit.aspx
Deleting Database Records with the Entity Framework
The final database operation, which we need to tackle in this tutorial, is deleting database records. You can use the controller action in Listing 6 to delete a particular database record.
https://cleverera405.weebly.com/blog/sea-of-thieves-download-mac. Listing 6 -- ControllersHomeController.cs (Delete action)
The Delete() action first retrieves the Movie entity that matches the Id passed to the action. Next, the movie is deleted from the database by calling the DeleteObject() method followed by the SaveChanges() method. Finally, the user is redirected back to the Index view.
Summary
The purpose of this tutorial was to demonstrate how you can build database-driven web applications by taking advantage of ASP.NET MVC and the Microsoft Entity Framework. You learned how to build an application that enables you to select, insert, update, and delete database records.
First, we discussed how you can use the Entity Data Model Wizard to generate an Entity Data Model from within Visual Studio. Next, you learn how to use LINQ to Entities to retrieve a set of database records from a database table. Finally, we used the Entity Framework to insert, update, and delete database records.
-->When working with Entity Framework Code First the default behavior is to map your POCO classes to tables using a set of conventions baked into EF. Sometimes, however, you cannot or do not want to follow those conventions and need to map entities to something other than what the conventions dictate.
There are two main ways you can configure EF to use something other than conventions, namely annotations or EFs fluent API. The annotations only cover a subset of the fluent API functionality, so there are mapping scenarios that cannot be achieved using annotations. This article is designed to demonstrate how to use the fluent API to configure properties.
The code first fluent API is most commonly accessed by overriding the OnModelCreating method on your derived DbContext. The following samples are designed to show how to do various tasks with the fluent api and allow you to copy the code out and customize it to suit your model, if you wish to see the model that they can be used with as-is then it is provided at the end of this article.
Model-Wide Settings
Default Schema (EF6 onwards)
Starting with EF6 you can use the HasDefaultSchema method on DbModelBuilder to specify the database schema to use for all tables, stored procedures, etc. This default setting will be overridden for any objects that you explicitly configure a different schema for.
Custom Conventions (EF6 onwards)
Starting with EF6 you can create your own conventions to supplement the ones included in Code First. For more details, see Custom Code First Conventions.
Property Mapping
The Property method is used to configure attributes for each property belonging to an entity or complex type. The Property method is used to obtain a configuration object for a given property. The options on the configuration object are specific to the type being configured; IsUnicode is available only on string properties for example.
Configuring a Primary Key
The Entity Framework convention for primary keys is:
- Your class defines a property whose name is “ID” or “Id”
- or a class name followed by “ID” or “Id”
To explicitly set a property to be a primary key, you can use the HasKey method. In the following example, the HasKey method is used to configure the InstructorID primary key on the OfficeAssignment type.
Configuring a Composite Primary Key
The following example configures the DepartmentID and Name properties to be the composite primary key of the Department type.
Switching off Identity for Numeric Primary Keys
The following example sets the DepartmentID property to System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None to indicate that the value will not be generated by the database.
Specifying the Maximum Length on a Property
In the following example, the Name property should be no longer than 50 characters. If you make the value longer than 50 characters, you will get a DbEntityValidationException exception. If Code First creates a database from this model it will also set the maximum length of the Name column to 50 characters.
Configuring the Property to be Required
In the following example, the Name property is required. If you do not specify the Name, you will get a DbEntityValidationException exception. If Code First creates a database from this model then the column used to store this property will usually be non-nullable.
Note
In some cases it may not be possible for the column in the database to be non-nullable even though the property is required. For example, when using a TPH inheritance strategy data for multiple types is stored in a single table. If a derived type includes a required property the column cannot be made non-nullable since not all types in the hierarchy will have this property.
Configuring an Index on one or more properties
Note
EF6.1 Onwards Only - The Index attribute was introduced in Entity Framework 6.1. If you are using an earlier version the information in this section does not apply.
Creating indexes isn't natively supported by the Fluent API, but you can make use of the support for IndexAttribute via the Fluent API. Index attributes are processed by including a model annotation on the model that is then turned into an Index in the database later in the pipeline. Sniper elite 3 license key generator. You can manually add these same annotations using the Fluent API.
The easiest way to do this is to create an instance of IndexAttribute that contains all the settings for the new index. You can then create an instance of IndexAnnotation which is an EF specific type that will convert the IndexAttribute settings into a model annotation that can be stored on the EF model. These can then be passed to the HasColumnAnnotation method on the Fluent API, specifying the name Index for the annotation.
For a complete list of the settings available in IndexAttribute, see the Index section of Code First Data Annotations. This includes customizing the index name, creating unique indexes, and creating multi-column indexes.
You can specify multiple index annotations on a single property by passing an array of IndexAttribute to the constructor of IndexAnnotation.
Specifying Not to Map a CLR Property to a Column in the Database
The following example shows how to specify that a property on a CLR type is not mapped to a column in the database.
Mapping a CLR Property to a Specific Column in the Database
C# Entity Framework
The following example maps the Name CLR property to the DepartmentName database column.
Renaming a Foreign Key That Is Not Defined in the Model
If you choose not to define a foreign key on a CLR type, but want to specify what name it should have in the database, do the following:
Configuring whether a String Property Supports Unicode Content
By default strings are Unicode (nvarchar in SQL Server). You can use the IsUnicode method to specify that a string should be of varchar type.
Configuring the Data Type of a Database Column
The HasColumnType method enables mapping to different representations of the same basic type. Using this method does not enable you to perform any conversion of the data at run time. Note that IsUnicode is the preferred way of setting columns to varchar, as it is database agnostic.
Configuring Properties on a Complex Type
There are two ways to configure scalar properties on a complex type.
You can call Property on ComplexTypeConfiguration.
You can also use the dot notation to access a property of a complex type.
Configuring a Property to Be Used as an Optimistic Concurrency Token
To specify that a property in an entity represents a concurrency token, you can use either the ConcurrencyCheck attribute or the IsConcurrencyToken method.
You can also use the IsRowVersion method to configure the property to be a row version in the database. Setting the property to be a row version automatically configures it to be an optimistic concurrency token.
Type Mapping
Specifying That a Class Is a Complex Type
By convention, a type that has no primary key specified is treated as a complex type. There are some scenarios where Code First will not detect a complex type (for example, if you do have a property called ID, but you do not mean for it to be a primary key). In such cases, you would use the fluent API to explicitly specify that a type is a complex type.
Specifying Not to Map a CLR Entity Type to a Table in the Database
The following example shows how to exclude a CLR type from being mapped to a table in the database.
Mapping an Entity Type to a Specific Table in the Database
All properties of Department will be mapped to columns in a table called t_ Department.
You can also specify the schema name like this:
Mapping the Table-Per-Hierarchy (TPH) Inheritance
In the TPH mapping scenario, all types in an inheritance hierarchy are mapped to a single table. A discriminator column is used to identify the type of each row. When creating your model with Code First, TPH is the default strategy for the types that participate in the inheritance hierarchy. By default, the discriminator column is added to the table with the name “Discriminator” and the CLR type name of each type in the hierarchy is used for the discriminator values. You can modify the default behavior by using the fluent API.
Mapping the Table-Per-Type (TPT) Inheritance
In the TPT mapping scenario, all types are mapped to individual tables. Properties that belong solely to a base type or derived type are stored in a table that maps to that type. Tables that map to derived types also store a foreign key that joins the derived table with the base table.
Mapping the Table-Per-Concrete Class (TPC) Inheritance
In the TPC mapping scenario, all non-abstract types in the hierarchy are mapped to individual tables. The tables that map to the derived classes have no relationship to the table that maps to the base class in the database. All properties of a class, including inherited properties, are mapped to columns of the corresponding table.
Call the MapInheritedProperties method to configure each derived type. MapInheritedProperties remaps all properties that were inherited from the base class to new columns in the table for the derived class.
Note
Entity Framework Auto Generate Key File
Note that because the tables participating in TPC inheritance hierarchy do not share a primary key there will be duplicate entity keys when inserting in tables that are mapped to subclasses if you have database generated values with the same identity seed. To solve this problem you can either specify a different initial seed value for each table or switch off identity on the primary key property. Identity is the default value for integer key properties when working with Code First.
Mapping Properties of an Entity Type to Multiple Tables in the Database (Entity Splitting)
Entity Framework Define Key
Entity splitting allows the properties of an entity type to be spread across multiple tables. In the following example, the Department entity is split into two tables: Department and DepartmentDetails. Entity splitting uses multiple calls to the Map method to map a subset of properties to a specific table.
Mapping Multiple Entity Types to One Table in the Database (Table Splitting)
The following example maps two entity types that share a primary key to one table.
Mapping an Entity Type to Insert/Update/Delete Stored Procedures (EF6 onwards)
Starting with EF6 you can map an entity to use stored procedures for insert update and delete. For more details see, Code First Insert/Update/Delete Stored Procedures.
Entity Framework No Primary Key
Model Used in Samples
Entity Framework Auto Generate Key In Spring Boot
The following Code First model is used for the samples on this page.