How to prevent DbContext from altering the database?

后端 未结 3 1435
广开言路
广开言路 2020-12-14 21:28

I\'m learning Entity Framework (currently using EF6 beta) and I\'m using the code first pattern on an existing database. The entities and DbContext class are cr

3条回答
  •  攒了一身酷
    2020-12-14 22:10

    I had this issue with DBFirst and EF 6.1 it was creating a new table based on the EntityName. So I modified the OnModelCreating virtual method to map my tables.

    So if the EntityName was named MyStuffs since by default the EnitityNames are pluralized which you do have the option to deselect that during the EF generation. In my case the wizard was generating the pluralized version of the table.

    public class MyContext: DbContext
    {
        public MyContext()
            : base("name=MyEntityConnectionName")
        {
        }
        public MyContext(string connectionString)
            : base(connectionString)
        {
        }
        #region methods
    
        public static MyContext Create()
        {
            return new MyContext();
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            // Map Entities to their tables.
            modelBuilder.Entity().ToTable("MyStuff"); //prevent a new table from being added since we added a mapping
        }
    
        #endregion
        public virtual DbSet MyEntities{ get; set; }
    }
    

提交回复
热议问题