EF Codefirst Learning Series III: SEED data

Source: Internet
Author: User

1. Write in front

In front of the database is automatically generated, some friends may find that this thing is not good use Ah, I worked hard to write a long time test data, automatically built a library when suddenly clear clean, and then test again painstakingly re-create, this is not deceptive! Well, you are right, it is very pit, I also feel very pit, so today we come to learn a better way.

2, open to engage

There are two ways to preserve test data, and here's the first: Create seed data.

Suppose such a scene, one day we are having a happy heart of the code, suddenly led to say: Ape Ape, first put your hands in the live put, here is a student management system is more urgent, first to engage in this. Although we are very unhappy to be interrupted, but in the spirit of Gong (Zi), but also accept, then start doing it.

Student management System Well, there must be a school monk Ah, so we first build a student class student:

 Public classStudent { Public intSId {Get;Set; }  Public stringName {Get;Set; }  Public intAge {Get;Set; }  Public VirtualIlist<course> Courses {Get;Set; } }

What the monks do every day, of course, class, so another course class course:

 Public classCourse { Public intCId {Get;Set; }  Public stringName {Get;Set; }  Public intSId {Get;Set; }  PublicStudent Student {Get;Set; } }

OK, first get these two on the line, first put the database up, configuration string, the database initialization set to Dropcreatedatabaseifmodelchanges (for this class detailed introduction and configuration please refer to the second article) mode, set up DbContext class, start .... Wait for the database to be built ~ ~ ~ However, the great journey will always have difficulties arise, it is not difficult to come, error, information as follows:

Course:EntityType:EntitySet ' Course ' is based on type ' Course ' This has no keys defined.
Student:EntityType:EntitySet ' Student ' is based on type ' Student ' This has no keys defined.

The meaning is that these two classes do not have a primary key, because the table is generally supposed to have a primary key, the only identity, check up also fast, no primary key EF do not give you work, forget, it wants us to give it Bai, but also can not dry with it, how to add it, two ways: set the characteristics and the method of rewriting .

The set attribute uses the key attribute under the namespace dataannotation to tell EF that a property is a primary key, such as:

[Key]  Public int Get set; }

The overriding method is the Onmodelcreating method in the DbContext class, such as:

protected Override void onmodelcreating (Dbmodelbuilder modelBuilder)        {            modelbuilder.entity<Student> (). Haskey (s = = s.sid);            Modelbuilder.entity<Course> (). Haskey (c = c.cid). Hasrequired (c = c.student). Withmany (s = = s.courses). Hasforeignkey (c = c.sid);             Base . Onmodelcreating (ModelBuilder);        }

Where the Haskey method is to set the model primary key.

Either of the two options, ok~ barrier exclusion, continue to start waiting for the database to build, this time no problem direct success:

Hey hey, wait, this is a good library? What about the seed data, the data? Don't worry, just step by step.

The Idatabaseinitializer interface defines a seed constraint that creates the seed data, the class that implements the interface has this method, and we build a class inheritance Dropcreatedatabasealways rebuild the library to implement the seed data creation.

public class dbinitializer:dropcreatedatabasealways<ggdbcontext>    {        protected override void  Seed (Ggdbcontext context)        {            context. Student.add (New Student () {Name = "Tom", Age=3});            Context. Student.add (New Student () {Name = "Angela", age = 2 });            Context. Course.add (New Course () {name = "Tickle", Student = new Student () {name = "Ben", age = n} });            Context. Course.add (New Course () {name = "fart", Student = new Student () {name = "Jimmy", age = 6 }}), base. Seed (context); } }

Then set the database initialization class to our custom class in Global.asax.

Database.setinitializer (New Dbinitializer ());

This allows you to automatically insert the data you added above into a table for testing and, of course, add more data to your database.

Yes, it is the initialization data we set. Spending!

3. Ending

OK, this article to the end of it, originally intended in this article will also record the data migration, but the sense of space is certainly larger, I personally look at the time is the most afraid of this voluminous article, learning efficiency will be very low, so intends to write in the next separate data migration, is the most important part, please look forward to Oh ~

  

EF Codefirst Learning Series III: SEED data

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.