ASP.NET身份DbContext混淆

默认代码MVC 5 App随IdentityModels.cs中的这段代码一起提供-此代码段用于默认模板的所有ASP.NET Identity操作:


public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

{

    public ApplicationDbContext()

        : base("DefaultConnection")

    {

    }

}

如果我使用带有Entity Framework的视图来搭建一个新的控制器并在对话框中创建一个“ New data context ...”,我将为我生成一个:


using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;


namespace WebApplication1.Models

{

    public class AllTheOtherStuffDbContext : DbContext

    {

        // You can add custom code to this file. Changes will not be overwritten.

        // 

        // If you want Entity Framework to drop and regenerate your database

        // automatically whenever you change your model schema, please use data migrations.

        // For more information refer to the documentation:

        // http://msdn.microsoft.com/en-us/data/jj591621.aspx


        public AllTheOtherStuffDbContext() : base("name=AllTheOtherStuffDbContext")

        {

        }


        public System.Data.Entity.DbSet<WebApplication1.Models.Movie> Movies { get; set; }


    }

如果我使用EF搭建另一个控制器+视图,例如为Animal模型,则此新行将在下面自动生成public System.Data.Entity.DbSet<WebApplication1.Models.Movie> Movies { get; set; }-像这样:


using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;


ApplicaionDbContext(适用于所有ASP.NET Identity东西)继承自IdentityDbContext,而继承自DbContext。 AllOtherStuffDbContext(用于我自己的东西)继承自DbContext。


所以我的问题是:


我所有其他自己的模型都应使用这两个(ApplicationDbContext和AllOtherStuffDbContext)中的哪个?还是我应该只使用默认值autogenerated,ApplicationDbContext因为使用它应该不是问题,因为它是从基类派生的DbContext,否则会产生一些开销吗?你应该只使用一个DbContext在你的应用程序为所有的车型(我读过这个地方)的对象,所以我不应该甚至考虑同时使用ApplicationDbContext,并AllOtherStuffDbContext在一个单一的应用程序?或带有ASP.NET Identity的MVC 5中的最佳实践是什么?


明月笑刀无情
浏览 593回答 3
3回答

茅侃侃

我将使用从IdentityDbContext继承的单个Context类。这样,您可以使上下文知道您的类与IdentityUser和IdentityDbContext的角色之间的任何关系。IdentityDbContext的开销很小,它基本上是带有两个DbSet的常规DbContext。一种用于用户,另一种用于角色。

缥缈止盈

如果深入研究IdentityDbContext的抽象,您会发现它看起来就像派生的DbContext。最简单的方法是Olav的答案,但是如果您想对创建的内容有更多的控制,并且对Identity软件包的依赖性较小,请在此处查看我的问答。如果您单击该链接,则会有一个代码示例,但总而言之,您只需将所需的DbSet添加到您自己的DbContext子类中。
打开App,查看更多内容
随时随地看视频慕课网APP