简体   繁体   中英

DBContext class ASP.Net MVC

I'm wondering how Entity framework knows which table to connect to, based on the following code:

    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public decimal Price { get; set; }
    }

    public class MovieDBContext : DbContext
    {
        public DbSet<Movie> Movies { get; set; }
    }

Source

I know that by default it connects to LocalDB. I can specify the database to connect to by adding an entry to Web.config file, like this:

<add name="MovieDBContext" 
   connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True" 
   providerName="System.Data.SqlClient" 
/> 

Now, the MovieDBContext class has a Movies property. Can I change its name without breaking anythig, or maybe this name is used by the framework to know which table to query?

What if I didn't add the code above to Web.config file? Would it create a Movies.mdf table automatically based on the name of property?

If you are usign Code First approach you can change name of Movies property. Entity framework uses class name (in this case class Movie ) to figure out table name.

By default it uses the following convention: Make a plural from class name and try to find such table in a database.

Regarding Database name: EF will try to create a database even if there is no connection string, but it will give a different name to it (eg WebApplication1.MovieDBContext ).

If your database has been already crearted using EF it may occur errors. So try to map your newly named class to the table explicitly .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM