Data annotation Attributes -- Key [Code-First series], -- keycode-first

Source: Internet
Author: User

Data annotation Attributes -- Key [Code-First series], -- keycode-first

The Key feature can be used in class attributes. The default Code-First Convention creates a primary Key with the attribute name "Id" or the class name + Id.

The Key feature overrides this default convention. You can apply the Key feature to a class attribute. No matter what the attribute name is, you can create a primary Key.

Let's take a look at the following code:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    [Table("StudentInfo")]   public class Student    {        [Key]        public int StudentKey { get; set; }        [Column("Name",TypeName="ntext")]        [MaxLength(20)]        public string StudentName { get; set; }        [NotMapped()]        public int? Age { get; set; }        public int StdId { get; set; }        [ForeignKey("StdId")]        public virtual Standard Standard { get; set; }    }}

In the preceding example, if the Key attribute is applied to the StudnetKey attribute of the Student object, the primary Key is obtained as follows:

 

Of course, you can also create a composite primary Key and use the Key and Column features to make the two columns serve as the primary Key at the same time. Let's look at the following code:

Note: Let's take a look at an incorrect example. When I create a composite primary Key, I only use the Key feature. Can I see it ???

View my code:

 

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    [Table("StudentInfo")]   public class Student    {        [Key]        public int StudentKey1 { get; set; }        [Key]        public int StudentKey2 { get; set; }        [Column("Name",TypeName="ntext")]        [MaxLength(20)]        public string StudentName { get; set; }        [NotMapped()]        public int? Age { get; set; }        public int StdId { get; set; }        [ForeignKey("StdId")]        public virtual Standard Standard { get; set; }    }}

Of course, we need to modify the calling code of the Main function:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    class Program    {        static void Main(string[] args)        {            Student stuModel = new Student() { StudentKey1 = 1,StudentKey2=1, StudentName = "cfs", StdId = 1 };            using (var db = new DbContextClass())            {                db.Students.Add(stuModel);                db.SaveChanges();            }            Console.WriteLine("Add Success");            Console.ReadKey();        }    }}

Run the program:

An error is reported. Check the specific error message:

Unable to determine composite primary key ordering for type 'ef2. Student '. Use the ColumnAttribute (see http://go.microsoft.com/fwlink? LinkId = 386388) or the HasKey method (see http://go.microsoft.com/fwlink? LinkId = 386387) to specify an order for composite primary keys.

You cannot create a composite primary key because the Column feature or the HasKey method is not used to specify the sequence of primary keys.

Then let's modify the code:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    [Table("StudentInfo")]   public class Student    {        [Key]        [Column]        public int StudentKey1 { get; set; }        [Key]        [Column]        public int StudentKey2 { get; set; }        [Column("Name",TypeName="ntext")]        [MaxLength(20)]        public string StudentName { get; set; }        [NotMapped()]        public int? Age { get; set; }        public int StdId { get; set; }        [ForeignKey("StdId")]        public virtual Standard Standard { get; set; }    }}

Now we have added the Column feature. Now we can run the program again:

We still carry the above error, and then modify the code:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    [Table("StudentInfo")]   public class Student    {        [Key]        [Column("one")]        public int StudentKey1 { get; set; }        [Key]        [Column("two")]        public int StudentKey2 { get; set; }        [Column("Name",TypeName="ntext")]        [MaxLength(20)]        public string StudentName { get; set; }        [NotMapped()]        public int? Age { get; set; }        public int StdId { get; set; }        [ForeignKey("StdId")]        public virtual Standard Standard { get; set; }    }}

 

This still doesn't work. Haha, because the column sequence is not specified, forget it, don't worry about it. The correct code is displayed:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF2{    [Table("StudentInfo")]   public class Student    {        [Key]        [Column(Order=1)]        public int StudentKey1 { get; set; }        [Key]        [Column(Order=2)]        public int StudentKey2 { get; set; }        [Column("Name",TypeName="ntext")]        [MaxLength(20)]        public string StudentName { get; set; }        [NotMapped()]        public int? Age { get; set; }        public int StdId { get; set; }        [ForeignKey("StdId")]        public virtual Standard Standard { get; set; }    }}

After running the program, check the database:

 

 

Note: For a single primary key, EF Code-First is created for us: the primary key increases automatically, while the compound primary key does not.

 

Of course, the key attribute can be applied not only to int type attributes, but also to strings and date types ..

Well, this is the Key feature of the Data Annotation Feature.

 

Related Article

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.