简体   繁体   English

DBContext类ASP.Net MVC

[英]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. 我知道默认情况下它连接到LocalDB。 I can specify the database to connect to by adding an entry to Web.config file, like this: 我可以通过向Web.config文件添加一个条目来指定要连接的数据库,如下所示:

<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. 现在,MovieDBContext类具有Movies属性。 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? 如果我没有将上面的代码添加到Web.config文件中怎么办? Would it create a Movies.mdf table automatically based on the name of property? 是否会根据属性名称自动创建Movies.mdf表?

If you are usign Code First approach you can change name of Movies property. 如果您使用的是“代码优先”方法,则可以更改Movies属性的名称。 Entity framework uses class name (in this case class Movie ) to figure out table name. 实体框架使用类名(本例中为class Movie )来确定表名。

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 ). 关于数据库名称:即使没有连接字符串,EF也会尝试创建数据库,但是它将给它一个不同的名称(例如WebApplication1.MovieDBContext )。

If your database has been already crearted using EF it may occur errors. 如果您的数据库已经使用EF进行过初始化,则可能会发生错误。 So try to map your newly named class to the table explicitly . 因此,尝试将新命名的类显式映射到表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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