小编Hug*_*ner的帖子

在MVC中根据请求使用Owin DbContext的实体框架

我注意到MVC的项目模板在使用单个用户帐户时会将一些对象放在当前的Owin上下文中(in App_Start/Startup.Auth.cs):

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
Run Code Online (Sandbox Code Playgroud)

看起来这是访问数据库的Identity功能.我的理解是,ApplicationDbContext每个请求创建一个单个实例,并通过整个管道重新使用.用我自己的实体框架做同样的事情是否有益DbContext

例如,我在以下位置创建了一个新文件App_Start/Startup.Data.cs:

public partial class Startup
{

    public void ConfigureData(IAppBuilder app)
    {

        app.CreatePerOwinContext(CreateParkingEntities);

    }

    protected ParkingEntities CreateParkingEntities()
    {
        return new ParkingEntities();
    }

}
Run Code Online (Sandbox Code Playgroud)

然后在Startup.cs:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
        ConfigureData(app);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我可以在我的控制器中使用上下文:

private ParkingEntities _db;

public ParkingEntities DbContext
{
    get
    {
        return …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc entity-framework dbcontext owin

5
推荐指数
1
解决办法
4475
查看次数

带有null selectList参数的Html.DropDownListFor

这是Add New Scaffolded Item...在创建新控制器时从VS获取的.

在控制器中:

// GET: Drivers/Create
public ActionResult Create()
{
    ViewBag.Tenant = new SelectList(db.Tenants, "TenantID", "TenantName");
    return View();
}
Run Code Online (Sandbox Code Playgroud)

然后该视图呈现一个下拉列表:

@Html.DropDownListFor(model => model.Tenant, null, htmlAttributes: new { @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)

相关型号信息:

public partial class Driver
{
    public int DriverID { get; set; }
    public int Tenant { get; set; }
    public virtual Tenant Tenant1 { get; set; }
}

public partial class Tenant
{
    public Tenant()
    {
        this.Drivers = new HashSet<Driver>();
    }

    public int TenantID …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc

4
推荐指数
1
解决办法
2469
查看次数

标签 统计

asp.net-mvc ×2

c# ×2

asp.net ×1

dbcontext ×1

entity-framework ×1

owin ×1