更新后的MVC5控制器创建更改ApplicationDbContext - 数据库

时间:2013-12-31 17:15:06

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

我的MVC5 VS2013项目中有一个复杂的数据模型。我可能会找到一种方法将它发布到某个地方,因为我在这个项目上有NDA。但是我会发布一些片段并尝试彻底解释这个问题。

我创建了一个基于模板的MVC5项目,并根据John Atten tutorial

执行更改

所以我有一个受保护的网站,角色,一些用户,以及使用mail,name和lastname扩展的ApplicationUser类。这非常有效。

然后我必须创建一个数据模型,用于存储注册用户的简历信息。这是一个非常复杂的模型。我创建了一个Client类,它有一个引用Application用户的外键。我会在下面张贴一次。还有许多其他外键引用性别,国家,城市等参考表。

IdentityModels.cs

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace CAEWebSite.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
    //ATENCIÓN
    //Cualquier cambio ejecutado en esta clase y en las demas clases que sean parte del modelo de datos, deben actualizar la base de datos así:
    //Add-Migration "UserAttributes"
    //Update-DataBase
    // UserAttributes puede ser usado siempre que se cmabie esta entidad
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string SecondLastName { get; set; }
    public string Email { get; set; }

    #region Navigation Properties
    public virtual ICollection<Client> Clients { get; set; }
    public virtual ICollection<Enterprise> Enterprises { get; set; } 
    #endregion


}

public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}

public class IdentityManager
{
    public bool RoleExists(string name)
    {
        var rm = new RoleManager<IdentityRole>(
            new RoleStore<IdentityRole>(new ApplicationDbContext()));
        return rm.RoleExists(name);
    }

    public bool CreateRole(string name)
    {
        var rm = new RoleManager<IdentityRole>(
            new RoleStore<IdentityRole>(new ApplicationDbContext()));
        var idResult = rm.Create(new IdentityRole(name));
        if (!idResult.Succeeded)
        {
            string errors = String.Empty;
            foreach (var error in idResult.Errors)
            {
                errors += error + ", "; ;
            }
            throw new Exception(errors);
        }
        return idResult.Succeeded;
    }

    public bool CreateUser(ApplicationUser user, string password)
    {
        var um = new UserManager<ApplicationUser>(
            new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var idResult = um.Create(user, password);
        if (!idResult.Succeeded)
        {
            string errors = String.Empty;
            foreach (var error in idResult.Errors)
            {
                errors += error + ", "; ;
            }
            throw new Exception(errors);
        }
        return idResult.Succeeded;
    }

    public bool AddUserToRole(string userId, string roleName)
    {
        var um = new UserManager<ApplicationUser>(
            new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var idResult = um.AddToRole(userId, roleName);
        if (!idResult.Succeeded)
        {
            string errors = String.Empty;
            foreach (var error in idResult.Errors)
            {
                errors += error + ", "; ;
            }
            throw new Exception(errors);
        }
        return idResult.Succeeded;
    }

    public void ClearUserRoles(string userId)
    {
        var um = new UserManager<ApplicationUser>(
            new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = um.FindById(userId);
        var currentRoles = new List<IdentityUserRole>();
        currentRoles.AddRange(user.Roles);
        foreach (var role in currentRoles)
        {
            um.RemoveFromRole(userId, role.Role.Name);
        }
    }
}
}

Client.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Identity.EntityFramework;
using System.ComponentModel.DataAnnotations;

namespace CAEWebSite.Models
{
public class Client
{
    public long ClientID { get; set; }

    #region Personal Data

    [Display(Name = "Fecha de nacimiento")]
    public DateTime BirthDate { get; set; }


    [Display(Name = "Género")]
    [ForeignKey("Genre")]
    public int GenreID { get; set; }


    [Display(Name = "Libreta militar")]
    public string ArmyCard { get; set; }

    [ForeignKey("DocumentType")]
    [Display(Name = "Tipo de documento")]
    public int DocumentTypeId { get; set; }


    [Display(Name = "Número de documento")]
    public string DocumentNumber { get; set; }

    [ForeignKey("BirthCountry")]
    [Display(Name = "País de nacimiento")]
    public long BirthCountryId { get; set; }

    [ForeignKey("BirthDepartment")]
    [Display(Name = "Departamento de nacimiento")]
    public long BirthDepartmentId { get; set; }

    [ForeignKey("BirthCity")]
    [Display(Name = "Ciudad de nacimiento")]
    public long BirthCityId { get; set; }

    [ForeignKey("FirstNationality")]
    [Display(Name = "Primera nacionalidad")]
    public long FirstNationalityId { get; set; }

    [ForeignKey("SecondNationality")]
    [Display(Name = "Segunda nacionalidad")]
    public long SecondNationalityId { get; set; }

    [ForeignKey("MarriageStatus")]
    [Display(Name = "Estado civil")]
    public int MarriageStatusId { get; set; }


    [Display(Name = "¿Es cabeza de hogar?")]
    public bool IsHouseHoldHead { get; set; }

    [ForeignKey("ApplicationUser")]
    public string ApplicationUserId { get; set; }
    #endregion

    #region Contact Data
    [ForeignKey("HomeCountry")]
    [Display(Name = "País de residencia")]
    public long HomeCountryId { get; set; }

    [ForeignKey("HomeDepartment")]
    [Display(Name = "Departamento de residencia")]
    public long HomeDepartmentId { get; set; }

    [ForeignKey("HomeCity")]
    [Display(Name = "Ciudad de residencia")]
    public long HomeCityId { get; set; }

    [Display(Name = "Dirección de residencia")]
    public string Address { get; set; }

    [Display(Name = "Barrio")]
    public string Neighborhood { get; set; }

    [Display(Name = "teléfono de residencia")]
    public string PhoneNumber { get; set; }

    [Display(Name = "teléfono celular")]
    public string CellPhoneNumber { get; set; }

    [Display(Name = "Observaciones")]
    public string Comments { get; set; }
    #endregion

    #region Work Experience

    [Display(Name = "¿Tiene experiencia laboral?")]
    public bool HasWorkExperience { get; set; }

    #endregion

    #region Work profile
    [Display(Name = "Perfil Profesional")]
    [DataType(DataType.MultilineText)]
    public string ProfessionalProfile { get; set; }

    [Display(Name = "Aspiración salarial mensual")]
    public int SalaryRangeId { get; set; }

    [Display(Name = "¿En búsqueda de?")]
    public int HireTypeId { get; set; }

    [Display(Name = "¿Interesado en teletrabajo?")]
    public bool IsHomeOfficeInterested { get; set; }

    [Display(Name = "Autorización de visualización de datos")]
    public int DataVisibilityLevelId { get; set; }
    #endregion

    #region Academic level

    [Display(Name = "Nivel")]
    [ForeignKey("ScholarLevel")]
    public int ScholarLevelId { get; set; }

    [ForeignKey("BasicKnowledgeCore")]
    [Display(Name = "Núcelo básico de conocimiento")]
    public int BasicKnowledgeCoreId { get; set; }

    [Display(Name = "Título")]
    public string Title { get; set; }

    [Display(Name = "Institución")]
    public string Institution { get; set; }

    [ForeignKey("EducationCountry")]
    [Display(Name = "País donde curó los estudios")]
    public long EducationCountryId { get; set; }

    [Display(Name = "¿Está graduado?")]
    public bool IsGraduated { get; set; }

    [Display(Name = "Año de graduación o retiro")]
    public int GraduationYear { get; set; }
    #endregion

    #region professional card
    [Display(Name = "Tarjeta profesional de...")]
    public string ProfessionalCardCareer { get; set; }

    [Display(Name = "Fecha de expedición")]
    public DateTime ProCardExpeditionDate { get; set; }

    [Display(Name = "Número de la tarjeta profesional")]
    public string ProCardNumber { get; set; }
    #endregion

    #region informal education
   //TODO Ricker Esperar correo de aclaracion de este punto. Tentativamente se dejan múltiples cursos

    public virtual ICollection<CapacitationCourse> CapacitationCourses { get; set; }

    #endregion

    #region Computer Knowledge
    public virtual ICollection<Skill> Skills { get; set; }

    #endregion

    #region Current work status
    [ForeignKey("WorkStatus")]
    public int WorkStatusID { get; set; }
    #endregion

    #region Languages
    [ForeignKey("Language")]
    public int LanguageId { get; set; }

    [ForeignKey("LanguageSkillLevel")]
    public int LanguageSkillLevelID { get; set; }

    #endregion

    #region driving license

    public int DrivingLicenseCategoryId { get; set; }

    public DateTime DrivingLicenceExpirationDate { get; set; }

    #endregion

    #region Handicap
    [ForeignKey("HandicapType")]
    public int HandicapTypeID { get; set; }

    public virtual ICollection<HazardousActivity> HazardousActivities { get; set; }

    public virtual ICollection<HazardousEnvironment> HazardousEnvironments { get; set; }
    #endregion

    #region Family
    public virtual ICollection<Relative> Relatives { get; set; }

    #endregion

    #region Foreign Keys
    public virtual HireType HireType { get; set; }

    public virtual SalaryRange SalaryRange { get; set; }

    public virtual DrivingLicenseCategory DrivingLicenseCategory { get; set; }

    public virtual HandicapType HandicapType { get; set; }

    public virtual Language Language { get; set; }

    public virtual LanguageSkillLevel LanguageSkillLevel { get; set; }

    public virtual Genre Genre { get; set; }

    public virtual DocumentType DocumentType { get; set; }

    [InverseProperty("BirthCityClients")]
    public virtual City BirthCity { get; set; }

    [InverseProperty("BirthDepartmentClients")]
    public virtual Department BirthDepartment { get; set; }

    public virtual MarriageStatus MarriageStatus { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }

    [InverseProperty("ClientBirthPlaces")]
    public virtual Country BirthCountry { get; set; }

    [InverseProperty("ClientFirstNationalities")]
    public virtual Country FirstNationality { get; set; }

    [InverseProperty("ClientSecondNationalities")]
    public virtual Country SecondNationality { get; set; }

    [InverseProperty("ClientHomeCountry")]
    public virtual Country HomeCountry { get; set; }

    [InverseProperty("HomeDepartmentClients")]
    public virtual Department HomeDepartment { get; set; }

    [InverseProperty("HomeCityClients")]
    public virtual City HomeCity { get; set; }

    [InverseProperty("ClientEducationCountry")]
    public virtual Country EducationCountry { get; set; }

    public virtual ScholarLevel ScholarLevel { get; set; }

    public virtual BasicKnowledgeCore BasicKnowledgeCore { get; set; }

    public virtual WorkStatus WorkStatus { get; set; }

    #endregion
}

public partial class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public System.Data.Entity.DbSet<Client> Client { get; set; }
}
}

一旦我完成所有模型,并检查并检查(可能仍需要一些检查)我添加了一个新的迁移(它显示了一些外键和类似的问题,但我解决了它们)并通过运行更新了dataBase update-database命令。

一切似乎都没问题,我在桌子上检查了一些钥匙,这是预期的。所以现在我创建了一个新的Client for Client,包括它的所有视图和所有内容。我希望有一个功能齐全的页面,但我没有。

Add Controller Dialog

当我运行应用程序(我成功编译)并转到客户端索引操作时,它会抛出此异常

  

发生了'System.InvalidOperationException'类型的异常   EntityFramework.dll但未在用户代码中处理

     

附加信息:每种类型的多个对象集不是   支持的。对象集'IdentityUsers'和'Users'都可以   包含'CAEWebSite.Models.ApplicationUser'类型的实例。

在客户端控制器的索引操作中抛出

public ActionResult Index()
    {
        var client = db.Client.Include(c => c.ApplicationUser).Include(c => c.BasicKnowledgeCore).Include(c => c.BirthCity).Include(c => c.BirthCountry).Include(c => c.BirthDepartment).Include(c => c.DocumentType).Include(c => c.DrivingLicenseCategory).Include(c => c.EducationCountry).Include(c => c.FirstNationality).Include(c => c.Genre).Include(c => c.HandicapType).Include(c => c.HireType).Include(c => c.HomeCity).Include(c => c.HomeCountry).Include(c => c.HomeDepartment).Include(c => c.Language).Include(c => c.LanguageSkillLevel).Include(c => c.MarriageStatus).Include(c => c.SalaryRange).Include(c => c.ScholarLevel).Include(c => c.SecondNationality).Include(c => c.WorkStatus);
        return View(client.ToList());
    }

再看看。创建Controller后,在ApplicationDbContext中,visual studio添加了下一行。

public System.Data.Entity.DbSet<CAEWebSite.Models.ApplicationUser> IdentityUsers { get; set; }

我不知道为什么,或者这意味着什么。但我认为它有一些事情要做。

我曾想过创建一个基于Client的简化视图模型来生成控制器,但我还没有。

我还会检查所有DbSet分配,它们看起来是正确的,除了一个Visual Studio创建。

我需要控制器工作,并解决异常中引发的问题,但我现在发现,是时候寻求帮助了。

新年快乐

0 个答案:

没有答案