用实体框架搭建MVC程序框架(全部)

 

第一步:1.新建项目

2.新建domain类库

3.新建Data类库

4.为上面的1.2.3添加实体框架nuget包。(可以右键管理nuget包来查找entityframework,当然也可以通过程序控制台)

Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.2.1

5.在Data类库中加入***Dbcontext文件。

 6.***Dbcontext里面的内容为

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.AspNet.Identity.EntityFramework;

using ***.Domain.Entities;

using ***.Domain.Entities.Map;

using ***.Domain.Entities.SalePromotion;



namespace ***.Data

{

    public class HappyGoDbcontext : IdentityDbContext<UserProfile>

    {

        public HappyGoDbcontext()

            : base("DefaultConnection")

        //: base("BaishunConnection")

        {

            Database.SetInitializer(new MigrateDatabaseToLatestVersion<HappyGoDbcontext, Migrations.Configuration>());







        }
   }
}

 7.如下图,Domain下新建文件夹Entity下加入UserProfile。并且继承 IdentityUser

 

 public class UserProfile : IdentityUser

    {

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserProfile> manager)

        {



            // 请注意,authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配

            var UserIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // 在此处添加自定义用户声明

            return UserIdentity;

        }

    }

 

 

 8.Data继承Domain类

9.***Dbcontext和UserProfile引用以下代码。

using Microsoft.AspNet.Identity.EntityFramework;

10.将***Dbcontext中的以下代码先注释开启自动迁移后取消注释。

11.开启自动迁移的办法。程序包控制台:enable-migrations如下图。

11.1 取消上面注释的代码。

12.IdentityConfig文件下的将原项目的Dbcontext 更换为ZzkjgDbcontext.同时将Web项目中的MOdel中的Identity删除,更换ApplicationUser为UserProfile.(全部)

 13.Web项目引用ninject mvc5。

Install-Package Ninject.MVC5

添加成功后将

 kernel.Bind<DbContext>().To<HappyGoDbcontext>().InRequestScope();

注册下。

14.在Configuration设置允许自动迁移。上线后关闭

  public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

你可能感兴趣的:(mvc)