Data Annotation Feature-InverseProperty, inverseproperty

Source: Internet
Author: User

Data Annotation Feature-InverseProperty, inverseproperty

We already know the default Code-First Convention. If you do not include the foreign key attribute in the parent class, then, the foreign Key {Class Name }_{ primary Key} will be created for us. This InverseProperty feature is used when there are multiple relationships between classes.

See the following code:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF3{   public class Student    {       public int StudentId { get; set; }       public string StudentName { get; set; }       public Standard CurrentStandard { get; set; }       public Standard PriviousStandard { get; set; }    }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EF3{   public class Standard    {       public int StandardId { get; set; }       public string StandardName { get; set; }       public ICollection<Student> CurrentStudent { get; set; }       public ICollection<Student> PreviousStudent { get; set; }    }}

In the code above, the Student object contains two Standard-type navigation attributes. The same Standard object contains two set-type Student navigation attributes, code-First creates four columns for their relationships:

 

 

The InverseProperty feature can override this default convention. In the following code, we can use the InverseProperty feature in Standard to fix this problem.

Let's take a look at the error example:

Using System; using System. collections. generic; using System. componentModel. dataAnnotations. schema; using System. linq; using System. text; namespace EF3 {public class Standard {public int StandardId {get; set;} public string StandardName {get; set ;}/// <summary> // InverseProperty, anti-attribute features // </summary> [InverseProperty ("one")] public ICollection <Student> CurrentStudent {get; set ;} /// <summary> /// InverseProperty, anti-attribute features /// </summary> [InverseProperty ("two")] public ICollection <Student> previusstudent {get; set ;}}}

In the anti-attribute feature above, I randomly enter non-existent characters, and then:

The message "CurrnentStudent" is invalid because the property one is not a valid Navigation property.

 

Then let's take a look at the correct code:

Using System; using System. collections. generic; using System. componentModel. dataAnnotations. schema; using System. linq; using System. text; namespace EF3 {public class Standard {public int StandardId {get; set;} public string StandardName {get; set ;}/// <summary> // InverseProperty, anti-attribute features // </summary> [InverseProperty ("CurrentStandard")] public ICollection <Student> CurrentStudent {get; set ;} /// <summary> /// InverseProperty, anti-attribute features /// </summary> [InverseProperty ("priviusstandard")] public ICollection <Student> previusstudent {get; set ;}}}

 

In this Code, enter the name of the navigation attribute in the Student object. You can.

 

Of course, you can use the foreign key feature to include the foreign key attribute. Please refer to the following code:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.Linq;using System.Text;using System.Threading.Tasks;namespace EF3{   public class Student    {       public int StudentId { get; set; }       public string StudentName { get; set; }       public int ForeignKeyCurrent { get; set; }       public int ForeignKeyPrevious { get; set; }       [ForeignKey("ForeignKeyCurrent")]       public Standard CurrentStandard { get; set; }        [ForeignKey("ForeignKeyPrevious")]       public Standard PriviousStandard { get; set; }    }}
Using System; using System. collections. generic; using System. componentModel. dataAnnotations. schema; using System. linq; using System. text; namespace EF3 {public class Standard {public int StandardId {get; set;} public string StandardName {get; set ;}/// <summary> // InverseProperty, anti-attribute features // </summary> [InverseProperty ("CurrentStandard")] public ICollection <Student> CurrentStudent {get; set ;} /// <summary> /// InverseProperty, anti-attribute features /// </summary> [InverseProperty ("priviusstandard")] public ICollection <Student> previusstudent {get; set ;}}}

Wait, do you think that's all you need? Let's run the program and check it out:

Naturally, an error occurred again. Let's take a look at the specific information:

Introducing the foreign key constraint 'fk _ dbo. Students_dbo.Standards_ForeignKeyPrevious 'into the table 'students' may cause loops or multiple cascade paths. Specify on delete no action or on update no action, or modify other foreign key constraints.
The constraint cannot be created. See the preceding error message.

 

Baidu: http://www.cnblogs.com/chear/archive/2012/11/09/2762145.html

Modify the code of the context class:

Using System; using System. collections. generic; using System. data. entity; using System. linq; using System. text; using System. threading. tasks; namespace EF3 {public class DbContextClass: DbContext {public DbContextClass (): base ("ConStr") {} public DbSet <Student> Studnets {get; set ;} public DbSet <Standard> Standards {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {Database. setInitializer (new DropCreateDatabaseIfModelChanges <DbContextClass> ());
// Add the code to cancel cascade deletion. (In fact, there can be two sentences of code. You can write only one sentence. Tested in person !!) ModelBuilder. Entity <Standard> (). HasMany (t => t. CurrentStudent). WithRequired (p => p. CurrentStandard). WillCascadeOnDelete (false );

ModelBuilder. Entity <Standard> (). HasMany (t => t. previusstudents). WithRequired (p => p. priviusstandard). WillCascadeOnDelete (false );

base.OnModelCreating(modelBuilder);     }    }}

Then run the program.

Thus, you can use InverseProperty and ForeignKey attribute for multiple relationships between the same classes.

Therefore, when there are multiple relationships, you can use the InverseProperty and foreign key features.

 

When we run the command, an error is returned, indicating whether the primary key conflicts with foreign keys. That is, there is no data in the primary key table Standard. We can simply insert two data entries.

After running;

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.