Entity Framework - CTP4 - Code First - How to turn off the automatic pluralization?

前端 未结 5 718
慢半拍i
慢半拍i 2021-01-01 00:20

My entity name is \"Contact\" and my table name is \"Contact\". However, the default pluralization support is making EF4 to look for a table named \"Contacts\". Anybody has

5条回答
  •  情歌与酒
    2021-01-01 01:01

    Out of the box, the code-first stuff will not modify or delete an existing database. I'm guessing you have an existing database that you either created manually or the framework created by running your program earlier, and then you changed your Contact class. The fast way to fix this error one time would be to manually delete your database, or update it to match your model.

    However, the real power of the code-first feature set is to allow rapid domain creation and refactoring without having to worry about creating and maintaining database scripts early in development. To do this, I personally have found it useful to allow the framework to delete my database for me every time I make a change to the model. Of course, that also means that I'd like to seed the database with test data.

    Here is how you can accomplish this:

    public class MyCustomDataContextInitializer : RecreateDatabaseIfModelChanges //In your case AddressBook
    {
        protected override void Seed(MyCustomDataContext context)
        {
            var contact = new Contact
            {
                ContactID = 10000,
                FirstName = "Brian",
                LastName = "Lara",
                ModifiedDate = DateTime.Now,
                AddDate = DateTime.Now,
                Title = "Mr."
            };
            context.Contact.Add(contact);
            context.SaveChanges();
        }
    }
    

    Then you need to register this initializer (say in Application_Start(), if it's a web application):

    Database.SetInitializer(new MyCustomDataContextInitializer());
    

    Note that you'll need:

    using System.Data.Entity.Infrastructure;
    

    Does this help?

提交回复
热议问题