How do I use System.ComponentModel.DataAnnotations

2019-02-12 17:51发布

问题:

Some time ago I asked this question: What is the purpose of each of the System.ComponentModel.DataAnnotations attributes?

However, I had no luck with getting replies. This question was a bit broad in the sense that it asked for documentation about every dataannotation attribute. At this moment, I am mostly interested in the Association attribute.

I am using ASP.NET MVC3 with Entity Framework 4 and would like to annotate my POCOs. I am using foreign keys in my POCOs (somehow feels wrong, but it seems to be generally accepeted). How do I annotate my POCO with the Association attribute? On which properties do I put it (Association property and/or foreign key property)? What are the thisKey and otherKey parameters. Is thisKey this POCOs key, or the foreign key in this POCO?

Then lastly, what will use this attribute? Is there something in ASP.NET MVC?

Thanks in advance!

回答1:

The AssociationAttribute (in conjuction with the ExternalReferenceAttribute) is used by WCF RIA Services in Silverlight. With this attribute the client can resolve associations between entities from diffrent Domains.

I think it is specific to RIA Services. Here´s a walkthrough how it gets applied in WCF RIA Services.

A simple Example looks like

public class Customer{
   public int Id {get;set;}
}

public class Order{

  public int Id {get;set;}

  public int CustomerId {get;set;}  //ForeignKey of the Customer

  [ExternalReference]
  [Association("Customer", "CustomerId", "Id")]
  public Customer {get;set;}
}


回答2:

Be aware that not all attributes provided in DataAnnotations namespace are related to Entity framework. I thought that AssociationAttribute is used in Linq-to-sql but it is actually different class with the same name from System.Data.Linq assembly. I just checked usage of AssociationAttribute by Reflector and it looks like neither Entity Framework (including code first), ASP.NET MVC, ASP.NET Dynamic data or WPF use it.