Configuration.cs文件asp.net 5 mvc

时间:2015-11-02 12:37:42

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

我正在尝试在ASP.NET 5 MVC上创建项目,所以我想在我的数据库中添加超级用户。在ASP.NET 4 MVC中,我的迁移文件夹中有Configuration.cs文件,我使用此代码在Seed方法中创建超级用户:

namespace WebApp.Migrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using WebApp.Models;

internal sealed class Configuration : DbMigrationsConfiguration<WebApp.Models.ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        // AutomaticMigrationsEnabled = true;
        // AutomaticMigrationDataLossAllowed = true;
    }

    protected override void Seed(WebApp.Models.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        var user = new ApplicationUser()
        {
            UserName = "***",
            Email = "***",
            Guid="0",
            EmailConfirmed = true
        };

        manager.Create(user, "***");

        if (roleManager.Roles.Count() == 0)
        {
            roleManager.Create(new IdentityRole { Name = "admin" });
        }

        var adminUser = manager.FindByName("***");

        manager.AddToRoles(adminUser.Id, new string[] { "admin" });
    }
  }
}

但我在新项目中找不到相同的文件。

enter image description here

some1可以帮助我吗? THX。

2 个答案:

答案 0 :(得分:4)

我假设您使用ASP.net 5默认模板,该模板使用ASP.NET MVC6和Entity Framework 7.从您的屏幕截图中我可以看到您有一个仅在EF7中引入的snapshot.cs文件。

尚未向Entity Framework 7添加种子配置选项(Beta 8),因此您需要创建自己的种子数据类并在应用启动时运行它。

要确定是否应该在数据库中播种它,可以运行Linq的Any()方法来确定表是否为空或改为使用自己的EF逻辑。

e.g。

proc expand

然后在public class DbSeedData { private MyDb _context; public DbSeedData(MyDb db) { _context = db; } public void EnsureSeedData() { if (!_context.Entities.Any()) { { _context.Entities.Add( new Entity{EntityName="blabla" }, new Entity{EntityName="blabla2" } ) } } }

添加到Startup.cs

ConfigureServices

将DBSeedData类添加到services.AddTransient<DbSeedData>(); 方法作为参数,例如

Configure

在此方法结束时添加:

public void Configure(IApplicationBuilder app, DbSeedData seeder, IHostingEnvironment env, ILoggerFactory loggerFactory)

答案 1 :(得分:1)

我不能代表MVC6,就像第一次谈论的那样,但是在MVC5中也可以做同样的事情。

在我的情况下,我不知道它是否在启用迁移时创建了configuration.cs文件,或者在另一点上创建了using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using WebSiteName.Models; using System; using System.Configuration; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; namespace WebSiteName.Migrations { internal sealed class Configuration : DbMigrationsConfiguration<WebSiteName.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(WebSiteName.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // Linq Method /* * var passwordHash = new PasswordHasher(); * string password = passwordHash.HashPassword("Password@123"); * context.Users.AddOrUpdate(u => u.UserName, * new ApplicationUser * { * UserName = "Steve@Steve.com", * PasswordHash=password, * PhoneNumber = "08869879" * * }); */ } } } 文件。但是,即使没有,您仍然可以创建一个。

在我的项目中,它创建了这个基本代码:

Public Sub application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    Dim strAddress As String
    Dim oRecipient As Recipient
    Dim strNextDueDate As String

    For Each oRecipient In Item.Recipients
        If oRecipient.Type = olTo Then

            ' Get the address
            strAddress = GetAddress(oRecipient)

            ' Check the adress for de
            If HasToBeChecked(strAddress) Then
                If InStr(1, Item.Body, LCase("next update due"), vbTextCompare) > 0 Then

                    'Get the value for the date.
                    strNextDueDate = GetStringBetweenStrings(Item.Body, "next update due:", vbCr)

                    ' ------------------------------------------
                    ' The rest of your code here.....
                    ' ------------------------------------------
                    'Call errhandler
                Else
                    'ask if we've added the date
                    prompt$ = "You're sending this to company x and have not added a 'next update due' date, do you need to add one?"
                    If MsgBox(prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check Address") = vbYes Then
                        Cancel = True
                    End If
                    Exit For
                End If
            End If
        End If
    Next

End Sub

' Fucntion to check if the address should be chnaged.
' We have it as a separate function so we can add more
' emails if needed.
Function HasToBeChecked(ByVal strAddress As String)

    Dim arrAddresses As Variant
    Dim i As Long
    Dim ret As Boolean

    ' Load the array of addresses
    arrAddresses = Array("relevantemail1@outlook.com", "relevantemail2@outlook.com")

    For i = LBound(arrAddresses) To UBound(arrAddresses)
        If LCase$(strAddress) = LCase$(arrAddresses(i)) Then
            ret = True
            Exit For
        End If
    Next i

    'Return the value
    HasToBeChecked = ret
End Function

' Function to retrive the address from a recipient object
Function GetAddress(ByRef oRecipient As Recipient) As String

    Const strSCHEMA_PROPERTY_TYPE As String = "http://schemas.microsoft.com/mapi/proptag/0x3002001F"

    Dim strAddresType As String
    Dim ret As String

    ' Get the address accoring to if it's an excahnge or a regular email
    strAddresType = oRecipient.PropertyAccessor.GetProperty(strSCHEMA_PROPERTY_TYPE)
    If addrType = "EX" Then
        ret = oRecipient.AddressEntry.GetExchangeUser.PrimarySmtpAddress
    Else
        ret = oRecipient.Address
    End If

    ' Return the value
    GetAddress = ret

End Function

' Function to get he string between teo strings
Function GetStringBetweenStrings(ByVal strToCheck As String, _
                                 ByVal strStart As String, _
                                 ByVal strEnd As String) As String

    Dim lPosStart As Long
    Dim lPostEnd As Long
    Dim ret As String

    lPosStart = InStr(1, strToCheck, strStart)
    If Not lPosStart = 0 Then
        lPosStart = lPosStart + Len(strStart) + 1
        lPostEnd = InStr(lPosStart, strToCheck, strEnd)

        If Not lPostEnd = 0 Then
            ret = Mid$(strToCheck, lPosStart, lPostEnd - lPosStart)
        End If
    End If

    ' Return the value
    GetStringBetweenStrings = ret

End Function

这是来自VS2013社区的MVC5模板/ w auth,仅供参考。这看起来与您使用的代码相同,但这在我的工作正常,您应该能够将任一代码复制到您的MVC5项目。我留下了linq评论给你,以防它帮助其他人。