EF code first dataannotations

Source: Internet
Author: User

The data Annotation Feature is introduced in. Net 3.5 and provides a method for adding and verifying classes in ASP. NET web applications. Code first allows you to use code to create an Entity Framework Model and use the data Annotation Feature to configure certain features of classes and attributes.

In fact, there are several useful articles in the previous articles. In this article, we will give a comprehensive introduction.

Key

The EF framework requires that each object must have a primary key field. It needs to track the object based on this primary key field. When creating an object, the codefirst method must also specify the primary key field. By default, the attribute is named ID, ID, or [classname] ID, if the primary key in the data table is mapped to a primary key without a similar name and the specified primary key is not displayed, the generation fails and an exception is thrown. If you want to customize the primary key column name, you can use the key Annotation

 [Key]
publicint MyId { get; set; }

Required

When the database is required to be in a field and cannot be blank

[Required]
publicstring BookTitle { get; set; }

Maxlength, minlength

Set the length range of database fields

   [MaxLength(10),MinLength(6)]
publicstring Password { get; set; }

Notmapped

When creating a data table, the Attribute Modified with this attribute is not created as a data table field.

    [NotMapped]
publicint MyProperty { get; set; }

Complextype

The complex attribute is the attribute that uses an object as another object. When mapped to a database, sub-objects are displayed as multiple attribute fields. For details, refer to: EF framework step by step (6)-processing entity complex attributes

    [ComplexType]
publicclass Publisher
{
publicstring PublisherName { get; set; }
publicstring PublisherAddress { get; set; }
} 

Concurrencycheck

Concurrent check allows you to identify one or more attributes when the object is updated, you need to check whether it is consistent with the original object. Concurrent checks are lazy in originalvalue. In Web applications, a user usually disconnects from the database after obtaining the data entity, if another user obtains an object and performs a new update operation, the initial user performs a concurrent check when the user updates the object. Based on the originalvalue of the identified concurrencycheck attribute, determine whether the original object exists. If the savechanges method does not exist, an exception is thrown in the savechanges method.

The following example shows that the booktitle attribute of the book object is identified as concurrencycheck.

    [Required,ConcurrencyCheck]
publicstring BookTitle { get; set; }

The following code simulates concurrency:

Book = dB. Books. Find (1 );
// Display indicates that the data entity has been modified
DB. Entry (book). State = system. Data. entitystate. modified;
DB. Entry (book). Property (B => B. booktitle). originalvalue = "dataannotations ";

// This code will cause an exception
DB. savechanges ();

Exceptions are thrown, such:

Using SQL profile monitoring, the database executes the following

update[dbo].[MyBook]
set[BookTitle]=@0
where (([MyId]=@1) and ([BookTitle]=@2))
', N'@0nvarchar(4000),@1int,@2nvarchar(4000)',
@0 = N'EF4.1 Code First', @1 = 1, @2 = N'DataAnnotations'

Timestamp and databasegenerated

Timestamp is a more common field for monitoring concurrency than concurrencycheck. In an object, a field of the byte array is usually used. One object class can only have one timestamp field, in addition, it is usually used in combination with databasegenerated. databasegenerated indicates that it is automatically generated by the database. It requires databasegeneratedoption enumeration as the parameter for database generation. The databasegeneratedoption enumeration contains three computed values automatically calculated, identity increases automatically, and none databases are not processed.

        [Timestamp,DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Byte[] TimeStamp { get; set; }

The usage of timestamp is similar to that of concurrencycheck.

 

Book = dB. Books. Find (1 );

// Simulate another user to update the same data entity
DB. database. executesqlcommand ("Update mybook set booktitle = 'ef 'Where myid = 1 ");

Book. booktitle = "New title ";
DB. savechanges ();

Similarly, in savechanges (), dbupdateconcurrencyexception is also thrown.

Table

By default, the codefirst method uses the complex object class name as the data table name. The table comment allows you to customize the table name.

    [Table("MyBook")]
publicclass Book

Column

By default, the codefirst method uses Entity class names as column names. Column annotations allow Custom column names and data types.

   [Column("BlogDescription", TypeName ="ntext")]
publicstring Description { get; set; }

Okay. Here is a comprehensive example. Let's take a look at the running result and take a look at it.

 

    [Table("MyBook")]
publicclass Book
{
[Key]
publicint MyId { get; set; }

[MaxLength(10), MinLength(6)]
publicstring KeyWord { get; set; }

[Required,MaxLength(50)]
publicstring BookTitle { get; set; }

[NotMapped]
publicint MyProperty { get; set; }

public Publisher Publisher { get; set; }

[Column("BlogDescription", TypeName ="ntext")]
publicstring Description { get; set; }

[Timestamp,DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Byte[] TimeStamp { get; set; }

}
[ComplexType]
publicclass Publisher
{
publicstring PublisherName { get; set; }
publicstring PublisherAddress { get; set; }
}

Generate data table

The data Annotation Feature is introduced in. Net 3.5 and provides a method for adding and verifying classes in ASP. NET web applications. Code first allows you to use code to create an Entity Framework Model and use the data Annotation Feature to configure certain features of classes and attributes.

In fact, there are several useful articles in the previous articles. In this article, we will give a comprehensive introduction.

Key

The EF framework requires that each object must have a primary key field. It needs to track the object based on this primary key field. When creating an object, the codefirst method must also specify the primary key field. By default, the attribute is named ID, ID, or [classname] ID, if the primary key in the data table is mapped to a primary key without a similar name and the specified primary key is not displayed, the generation fails and an exception is thrown. If you want to customize the primary key column name, you can use the key Annotation

 [Key]
publicint MyId { get; set; }

Required

When the database is required to be in a field and cannot be blank

[Required]
publicstring BookTitle { get; set; }

Maxlength, minlength

Set the length range of database fields

   [MaxLength(10),MinLength(6)]
publicstring Password { get; set; }

Notmapped

When creating a data table, the Attribute Modified with this attribute is not created as a data table field.

    [NotMapped]
publicint MyProperty { get; set; }

Complextype

The complex attribute is the attribute that uses an object as another object. When mapped to a database, sub-objects are displayed as multiple attribute fields. For details, refer to: EF framework step by step (6)-processing entity complex attributes

    [ComplexType]
publicclass Publisher
{
publicstring PublisherName { get; set; }
publicstring PublisherAddress { get; set; }
} 

Concurrencycheck

Concurrent check allows you to identify one or more attributes when the object is updated, you need to check whether it is consistent with the original object. Concurrent checks are lazy in originalvalue. In Web applications, a user usually disconnects from the database after obtaining the data entity, if another user obtains an object and performs a new update operation, the initial user performs a concurrent check when the user updates the object. Based on the originalvalue of the identified concurrencycheck attribute, determine whether the original object exists. If the savechanges method does not exist, an exception is thrown in the savechanges method.

The following example shows that the booktitle attribute of the book object is identified as concurrencycheck.

    [Required,ConcurrencyCheck]
publicstring BookTitle { get; set; }

The following code simulates concurrency:

Book = dB. Books. Find (1 );
// Display indicates that the data entity has been modified
DB. Entry (book). State = system. Data. entitystate. modified;
DB. Entry (book). Property (B => B. booktitle). originalvalue = "dataannotations ";

// This code will cause an exception
DB. savechanges ();

Exceptions are thrown, such:

Using SQL profile monitoring, the database executes the following

update[dbo].[MyBook]
set[BookTitle]=@0
where (([MyId]=@1) and ([BookTitle]=@2))
', N'@0nvarchar(4000),@1int,@2nvarchar(4000)',
@0 = N'EF4.1 Code First', @1 = 1, @2 = N'DataAnnotations'

Timestamp and databasegenerated

Timestamp is a more common field for monitoring concurrency than concurrencycheck. In an object, a field of the byte array is usually used. One object class can only have one timestamp field, in addition, it is usually used in combination with databasegenerated. databasegenerated indicates that it is automatically generated by the database. It requires databasegeneratedoption enumeration as the parameter for database generation. The databasegeneratedoption enumeration contains three computed values automatically calculated, identity increases automatically, and none databases are not processed.

        [Timestamp,DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Byte[] TimeStamp { get; set; }

The usage of timestamp is similar to that of concurrencycheck.

 

Book = dB. Books. Find (1 );

// Simulate another user to update the same data entity
DB. database. executesqlcommand ("Update mybook set booktitle = 'ef 'Where myid = 1 ");

Book. booktitle = "New title ";
DB. savechanges ();

Similarly, in savechanges (), dbupdateconcurrencyexception is also thrown.

Table

By default, the codefirst method uses the complex object class name as the data table name. The table comment allows you to customize the table name.

    [Table("MyBook")]
publicclass Book

Column

By default, the codefirst method uses Entity class names as column names. Column annotations allow Custom column names and data types.

   [Column("BlogDescription", TypeName ="ntext")]
publicstring Description { get; set; }

Okay. Here is a comprehensive example. Let's take a look at the running result and take a look at it.

 

    [Table("MyBook")]
publicclass Book
{
[Key]
publicint MyId { get; set; }

[MaxLength(10), MinLength(6)]
publicstring KeyWord { get; set; }

[Required,MaxLength(50)]
publicstring BookTitle { get; set; }

[NotMapped]
publicint MyProperty { get; set; }

public Publisher Publisher { get; set; }

[Column("BlogDescription", TypeName ="ntext")]
publicstring Description { get; set; }

[Timestamp,DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public Byte[] TimeStamp { get; set; }

}
[ComplexType]
publicclass Publisher
{
publicstring PublisherName { get; set; }
publicstring PublisherAddress { get; set; }
}

Generate data table

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.