【问题标题】:Replacing DbContext in Microsoft MVC Individual User Accounts Template替换 Microsoft MVC 个人用户帐户模板中的 DbContext
【发布时间】:2016-03-30 14:11:22
【问题描述】:

我刚刚创建了我的第一个 MVC 网站。 为避免自己对控制器进行编程,我使用了 Microsoft 的 Individual User Accounts 模板。

我知道,这个模板使用实体框架来创建一个快速数据库来保存用户/帐户数据。

由于我已经有一个要使用的数据库,因此我想更改 模板,因此它将 DbContext 用于所述数据库。

我能够更改连接字符串,以便在我的数据库中创建模板的表。但我不希望它创建自己的表,而是使用我已经创建的表。

有什么简单的方法可以实现吗?

还是我应该自己从头开始编写整个帐户/用户控制器?

【问题讨论】:

  • But I don't want it to create it's own tables but use my already created tables 看我下面的回答Database.SetInitializer<YourContext>(null);

标签: c# asp.net-mvc entity-framework asp.net-mvc-5


【解决方案1】:
// This is an example of DbContext class  it implements DbContext
// If you do not use constructor(s) then the expectation by entity framework
// will be that your name of your connectionstring in web.config 
// or app.config is name name as your class  so e.g.  "YourContext",                        
// otherwise   "Name="YourConnectionString"
public class YourContext : DbContext
{
    // constructor as you wish /want 
    public YourContext(string nameOrConnectionString)
        : base(nameOrConnectionString)
        { }  

    // critical mapping 
    public DbSet<someModel> someModel { get; set; }

    // critical overide 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // critical key to NOT let your database get dropped or created etc...
        Database.SetInitializer<YourContext>(null);

        // This is an example of mapping model to table 
        // and also showing use of a schema ( dbo  or another )
        modelBuilder.Entity<someModel>().ToTable("someTable", schemaName: "dbo");

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 2018-07-11
    • 1970-01-01
    • 2022-08-24
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多