Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC5 controller creation altering ApplicationDbContext after update-Database
    text
    copied!<p>I have a complex data model in my MVC5 VS2013 project. I may find a way to post it somewhere, since I have NDA on this project. However I´ll post some snippets and try to explain the issue, thoroughly.</p> <p>I created a template based MVC5 project and perform the changes according to <a href="http://typecastexception.com/post/2013/11/11/Extending-Identity-Accounts-and-Implementing-Role-Based-Authentication-in-ASPNET-MVC-5.aspx-in-ASPNET-MVC-5.aspx" rel="nofollow noreferrer">John Atten tutorial</a></p> <p>So I have a site with protected sing up, roles, some users, and the ApplicationUser class extended with mail, name and lastname. That perfectly worked.</p> <p>then I have to create a data model for storing curriculum vitae information for registered users. This is a very complex model. I created a Client class, which has a foreign key referring Application user. I´ll post the once below. And many other foreign keys referring reference tables like gender, countries, cities and so on.</p> <p>IdentityModels.cs</p> <pre><code>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&lt;Client&gt; Clients { get; set; } public virtual ICollection&lt;Enterprise&gt; Enterprises { get; set; } #endregion } public partial class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt; { public ApplicationDbContext() : base("DefaultConnection") { } } public class IdentityManager { public bool RoleExists(string name) { var rm = new RoleManager&lt;IdentityRole&gt;( new RoleStore&lt;IdentityRole&gt;(new ApplicationDbContext())); return rm.RoleExists(name); } public bool CreateRole(string name) { var rm = new RoleManager&lt;IdentityRole&gt;( new RoleStore&lt;IdentityRole&gt;(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&lt;ApplicationUser&gt;( new UserStore&lt;ApplicationUser&gt;(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&lt;ApplicationUser&gt;( new UserStore&lt;ApplicationUser&gt;(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&lt;ApplicationUser&gt;( new UserStore&lt;ApplicationUser&gt;(new ApplicationDbContext())); var user = um.FindById(userId); var currentRoles = new List&lt;IdentityUserRole&gt;(); currentRoles.AddRange(user.Roles); foreach (var role in currentRoles) { um.RemoveFromRole(userId, role.Role.Name); } } } } </code></pre> <p>Client.cs</p> <pre><code>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&lt;CapacitationCourse&gt; CapacitationCourses { get; set; } #endregion #region Computer Knowledge public virtual ICollection&lt;Skill&gt; 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&lt;HazardousActivity&gt; HazardousActivities { get; set; } public virtual ICollection&lt;HazardousEnvironment&gt; HazardousEnvironments { get; set; } #endregion #region Family public virtual ICollection&lt;Relative&gt; 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&lt;ApplicationUser&gt; { public System.Data.Entity.DbSet&lt;Client&gt; Client { get; set; } } } </code></pre> <p>Once I finish all the model, and review it and checked (some check may still be needed) I added a new migration (it showed some foreign keys and issues like that, but I solved them) and updated the dataBase by running update-database command.</p> <p>Everything seem ok, I checked the tables ad some keys and it was a expected. So now I created a new Controller for Client, with all its views and everything. I hoped to have a fully functional page, but I did not.</p> <p><img src="https://i.stack.imgur.com/4xnaz.png" alt="Add Controller Dialog"></p> <p>When I run the app (I compiled it successfully) and go to Client Index action, it throws this exception</p> <blockquote> <p>An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code</p> <p>Additional information: Multiple object sets per type are not supported. The object sets 'IdentityUsers' and 'Users' can both contain instances of type 'CAEWebSite.Models.ApplicationUser'.</p> </blockquote> <p>Thrown in the Index Action of Client Controller</p> <pre><code>public ActionResult Index() { var client = db.Client.Include(c =&gt; c.ApplicationUser).Include(c =&gt; c.BasicKnowledgeCore).Include(c =&gt; c.BirthCity).Include(c =&gt; c.BirthCountry).Include(c =&gt; c.BirthDepartment).Include(c =&gt; c.DocumentType).Include(c =&gt; c.DrivingLicenseCategory).Include(c =&gt; c.EducationCountry).Include(c =&gt; c.FirstNationality).Include(c =&gt; c.Genre).Include(c =&gt; c.HandicapType).Include(c =&gt; c.HireType).Include(c =&gt; c.HomeCity).Include(c =&gt; c.HomeCountry).Include(c =&gt; c.HomeDepartment).Include(c =&gt; c.Language).Include(c =&gt; c.LanguageSkillLevel).Include(c =&gt; c.MarriageStatus).Include(c =&gt; c.SalaryRange).Include(c =&gt; c.ScholarLevel).Include(c =&gt; c.SecondNationality).Include(c =&gt; c.WorkStatus); return View(client.ToList()); } </code></pre> <p>Taking a second look. Once the Controller was created,in the ApplicationDbContext, visual studio added the next line.</p> <pre><code>public System.Data.Entity.DbSet&lt;CAEWebSite.Models.ApplicationUser&gt; IdentityUsers { get; set; } </code></pre> <p>I don´t know why, or what this means. But I think it has something to do.</p> <p>I have thought of creating a simplified viewmodel based on Client to generate controller from that, but I haven´t yet.</p> <p>I also review all DbSet assignation and they appear to be correct, except for the one visual studio created.</p> <p>I need the controller to work, and solve the issue thrown in the exception some how but I find right now, it is time for ask for help.</p> <p>Happy new year</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload