EntityFramework Code-first Easy Tutorial (vi)-------domain class configuration dataannotations

Source: Internet
Author: User

EF Code-first provides a collection of dataannotation attributes that can be used on a domain class or its properties, and the Dataannotation attribute overrides the default EF conventions.

Dataannotation exists in two namespaces:

System.ComponentModel.DataAnnotations and System.ComponentModel.DataAnnotations.Schema

Note: DataAnnotations only provides a subset of the configuration options, all of the configuration options in the Fluent API.

System.ComponentModel.DataAnnotations contains the following features:
Attribute Description
Key Mark an attribute that will be mapped to a primary key in the relational table
Timestamp Marks a property that will be mapped to a non-nullable tiamestamp (timestamp) column in the database
Concurrencycheck This property allows you to mark one or more attributes, and the tagged attributes will be checked concurrently when the user edits or deletes the entity.
Required Mandatory constraint, this property must have data and cannot be null (same applies to MVC)
MinLength Ensure that the array or string length reaches the minimum length
MaxLength Maximum number of columns in a database
Stringlength Specify the maximum allowable length and minimum length of a character in a data field
System.ComponentModel.DataAnnotations.Schema contains the following features:
Attribute Description
Table Specifies the table name that is generated by the mapped class in the database
Column Specify the column name and data type of the mapped property in the table
Index Create an index on the specified column (only EF6.1 or later)
ForeignKey Specifying foreign key properties for navigation properties
notmapped Tagged properties are not mapped to the database
databasegenerated The specified property will be mapped to a computed column in the database table, so this property should be read-only. can also be used to map attributes to identity columns (self-growing columns)
Inverseproperty When there are multiple relationships between two classes, the default convention arranges the combination of their navigation properties and creates the foreign keys one by one, Inverseproperty can mark the actual primary foreign key relationship, thus filtering out the useless foreign keys that are combined by the permutation.
ComplexType Mark a class as a complex type

Let's take a detailed description of each feature:Key:

The key attribute is applied to the properties of a class. Code-first the default convention is to create a property with the name "id" or the {class name}+ "id" as a primary key column, and the key attribute to overwrite the default convention, we can mark any attribute of the primary key that we want to be a key regardless of its name.

The code is as follows:

using System.ComponentModel.DataAnnotations;  Public class student{    public  Student ()    {             }    [Key]    publicint  getset;}           Public string Get Set ; }        }

In the database, the Studentkey column in the students table is created as the primary key

We can also use the key attribute and the column attribute to create a mixed primary key, as shown in the following code:

usingSystem.ComponentModel.DataAnnotations; Public classstudent{ PublicStudent () {} [Key] [Column (Order=1)]     Public intStudentKey1 {Get;Set; }    [Key] [Column (Order=2)]     Public intStudentKey2 {Get;Set; }  Public stringStudentname {Get;Set; } }

Based on the code above, the mixed primary key StudentKey1 and StudentKey2 are created in the students table.

Note: When the key attribute is applied to attributes of a single integer type, it is created as an identity column, and the mixed key does not create an identity column, regardless of whether it is an integer type. The key feature, in addition to unsigned integer (unsinged integers), can be applied on any data type such as String, Datatime, Decimal, and so on.

TimeStamp:

The timestamp attribute can only be used on a property with a data type of byte array, and the timestamp attribute creates a timestamp property column in the database table Code-first automatically uses the timestamp column for concurrency checking.

(For concurrency checks, refer to Gyoung's notes: Entity Framework concurrency Processing)

The code is as follows:

usingSystem.ComponentModel.DataAnnotations; Public classstudent{ PublicStudent () {} Public intStudentkey {Get;Set; }  Public stringStudentname {Get;Set; } [TimeStamp] Public byte[] RowVersion {Get;Set; }}

Again, the attribute type that marks the timestamp attribute must be a byte array.

In this way, the rowversion column is created as a timestamp (timestamp) in the Database Students table.

Concurrencycheck:

When EF executes the update command on a table, Code-first inserts the values in the column labeled the Concurrencycheck attribute into the "where" clause of the SQL statement for concurrency checking. The following code:

 using   System.ComponentModel.DataAnnotations;  public  class   student{  Student () {}  public  int StudentID {get ; set           public  string  studentname {get ; set   

As shown above, the Concurrencycheck attribute is marked on the Studentname property, so Code-first will include the Studentname column in the update command for optimistic concurrency checking (for optimistic concurrency and pessimistic concurrency, The above Gyoung notes are introduced, here is not much discussion). As shown in the following code:

execsp_executesql N'UPDATE [dbo]. [Students] SET [Studentname] = @0where ([[StudentID] = @1) and ([studentname] = @2))'N'@0 nvarchar (max), @1 int,@2 nvarchar (max)',@0=N'Steve',@1=1,@2=N'Bill'Go                   

Note: The timestamp attribute can only be used on single byte array properties, whereas the Concurrencycheck attribute may be used on any number and property of any data type.

First sleep, the rest of the holiday to write ...

EntityFramework Code-first Easy Tutorial (vi)-------domain class configuration dataannotations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.