locked
Error when IdentityDbContext uses EDMX entities from the General Context RRS feed

  • Question

  • I have a solution divided into several projects. Part in Windows Forms and part in ASP.MVC. The structure, simplified for example, is as follows: MyProject.EF.DataBase.SQL (here is the EDMX) MyProject.WEB.MVC (here is Identity)

    The entire solution uses the context and the connection string DataBase First that is in MyProject.EF.DataBase.SQL.

    And for Identity I have created a proper string connection so that Web.config has:

    <connectionStrings>
    <add name="MyProjectEntities" connectionString="metadata=res://*/GPSd_BD.csdl|res://*/GPSd_BD.ssdl|res://*/GPSd_BD.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDb)\MSSQLLocalDB;initial catalog=GPSd;user id=sa;password=xxx;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    <add name="IdentityConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=GPSd;user id=sa;password=xxx;" providerName="System.Data.SqlClient" />

    I used these 2 tutorials to integrate AspNetUsers with Id INT into my database. But I have a little problem, which I do not understand.

    https://danieleagle.com/2014/05/setting-up-asp-net-identity-framework-2-0-with-database-first-vs2013-update-2-spa-template/

    https://docs.microsoft.com/en-us/aspnet/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity

    All because my AspNetUsers has relationships with several other entities, so ... To refer to them in my ApplicationDbContext DbSet (Identity context), if I make a copy of the EDMX entity within the MVC Models folder, the system works perfectly. But if I try to reference entities directly from EDMX I start having a lot of erros, like:

    System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation: GPSd.Web.MVC.Models.AspNetUserLogins: : EntityType 'AspNetUserLogins' has no key defined. Define the key for this EntityType. AspNetUserLogins: EntityType: EntitySet 'AspNetUserLogins' is based on type 'AspNetUserLogins' that has no keys defined.

    If I solve this overhide OnModelCreate I have other and other... I've never seen anything like it ... How can I solve this, so that I do not have to copy my EDMX to the Models folder?

    //using WEB.MVC.Models;   //<---If I use this Work fine!
    //using MyProject.EF.DataBase.SQL;   //<---If I use this I have validation errors were detected during model generation
    namespace GPSd.Web.MVC.Models
    {
    public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    
        public string LOGIN { get; set; }
        //public int IDUNIDADE { get; set; } By test I'm trying only 1 relation for time
        //public int IDPESSOA { get; set; }
    
        [ForeignKey("STATUS_REGISTROS")]
        public int IDSTATUSREGISTRO { get; set; }
    
        public virtual STATUS_REGISTROS STATUS_REGISTROS { get; set; }
    
    }
    
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public ApplicationDbContext()
            : base("IdentityConnection")
        {
        }
    
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    
        public virtual DbSet<STATUS_REGISTROS> STATUS_REGISTROS { get; set; }
    } 
    }

    Edited here ------------------------------------------

    Looking back, I realized that what I said was not entirely correct. Because when I copied the EDMX entity, I removed the virtual ICollection methods to simplify the example. It turns out that one of these ICollection refers to a relationship from the AspNetUsers table.

    By doing more tests and according to the relationships of my system I realized that when one of the Identity tables is mentioned, then I get my errors:

    -ApplicationUser 'and' AspNetUsers' can not share table 'AspNetUsers'

    -'AspNetUserLogins' dont have a key definition

    - etc, etc

    Adding the code of such entity I am copying:

    public partial class STATUS_REGISTROS
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public STATUS_REGISTROS()
        {
            this.AspNetUsers = new HashSet<AspNetUsers>();
            this.HOLDINGS_GRUPOS = new HashSet<HOLDINGS_GRUPOS>();
            this.UNIDADES = new HashSet<UNIDADES>();
        }
    
        public int ID { get; set; }
        public string DESCRICAO { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AspNetUsers> AspNetUsers { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HOLDINGS_GRUPOS> HOLDINGS_GRUPOS { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<UNIDADES> UNIDADES { get; set; }
    }
    • Edited by AlamBique Thursday, November 23, 2017 1:43 PM Adding New Findings to Explanation
    • Moved by 宝宝徐 Friday, December 1, 2017 6:21 AM
    Thursday, November 23, 2017 11:15 AM

All replies

  • Hi AlamBique,

    Welcome to MSDN forum.

    Please go to Microsoft asp.net MVC forum to open a new thread to talk about your problems where you will get more professional support about asp.net. If you have problems about visual studio IDE, please feel free to let me know.

    Best regards,

    Joyce


    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, November 24, 2017 5:56 AM