Entity Framework Code First (3) Data Annotations, entityannotations
Entity FrameworkCode FirstUsing a convention (Conventions) Better than the configuration (Configuration) Programming mode allows you to use your ownDomain classesTo indicateEFThe dependent model executes the query, change tracking, and update functions, which means that yourDomain classesMust followEFConventions used. However, if yourDomain classesCannot followEFIn this case, you need to be able to add some configurations to make yourClassesYesEFRequired information.
Code FirstYou can configure your class in two ways:
- DataAnnotations, Using simple attributes;
- Fluent APITo describe your configuration in the way of programming commands.
This article will focus onDataAnnotations(In the namespaceSystem. ComponentModel. DataAnnotations)
For the convenience of examples, we first create two classes:BlogAndPost
The above classes follow the conventions, but you can also useAnnotationsIsEFProvide more information
Key primary Key
EFEach object has a primary key to track objects. In the conventions, the primary key is queried byIDOrClassName + ID. What if the class does not have such attributes? We transform the class as follows (IdChangePrimaryTrackingKey)
If we addScaffoldedThe following error occurs:
We need to useKey annotationDetermine which attribute is the primary key
We useCode First's Database GenerationFunction to check the database
Required is not empty
Used to indicate that the field is not empty
Run and check the result.
Let's take a look at the background database.
MaxLength and MinLength
As the name implies, it is to limit the length of a field.
Check the background database
Run to view results
Ignore NotMapped
Some attributes in the class, such as those obtained by computation or merged by other columns, do not want them to be recorded in the database.NotMapped Annotation
The same is true for classes.
ComplexType complex type
Generally, this is not common: A class contains another class, that is, a complete object is described by a set of classes. For example, we addBlogDetailsClass
Note:BlogDetailsIt does not contain any primary key attribute. It is called a value object in the domain-driven design.EFIs called complex type (ComplexType).Complex TypesWe cannot track ourselves, but we canComplexType AnnotationTo change this embarrassment.
We can see that tables in the databaseBlogIncludeBlogDetailsThe default column name prefix isComplex typeThat isBlogDetails
ConcurrencyCheck concurrency check
ConcurrencyCheck AnnotationYou can set a tag on one or more attributes to perform concurrent checks when a user updates or deletes an object.
If this column is updated at the same time, an exception is thrown.DbUpdateConcurrencyException
TimeStamp
The row version number or timestamp is usually used to check concurrency, exceptConcurrencyCheck Annotation,You can also use more preciseTimsStamp,The premise is that the attribute type is byte array (Byte array).Code FirstTreatTimsStampAttributes andConcurrencyCheckThe attributes are the same, but the fields generated in the database areNon-nullable
Only one of the given classes can be created.TimsStampAttribute
Check the background database
Table and Column Table/Column name
Specify the table/column name matching the database
The table/column name has been changed.
DatabaseGenerated self-growth
DatabaseGeneratedOptionThere are three options:
- DatabaseGeneratedOption.Computed: In useCode FirstWhen creating a database, you canByteOrTimestampColumn usageDatabaseGenerated AnnotationOtherwise, it should be used when the database exists. Because if the database does not existCode FirstUnknown as a computed column (Computed Column) Select the formula to use.
- DatabaseGeneratedOption.Identity: If the primary key isIntegerType, the database is automatically increased by default (the effect is equivalent to the setting)DatabaseGeneratedOption. Identity), If the primary key isGUIDType, you must explicitly set auto-Increment
- DatabaseGeneratedOption.None: You can set itDatabaseGeneratedOption. None
ForeignKey
Look at the database
InverseProperty property inversion
InversePropertyIt is generally used when there are multiple relationships between classes.
For examplePostYou may need to track not only who wrote but also who edited the blog.
At this time, you will see that the background database has four foreign keysPerson_Id, Person_Id1, CreatedBy_Id and UpdatedBy_Id
To solve this problem, we can use InverseProperty annotationTo clarify the direction between attributes.
Let's look at the database again. The situation has changed.
Original article:Http://msdn.microsoft.com/en-us/data/jj591583
Reference page: http://qingqingquege.cnblogs.com/p/5933752.html