简体   繁体   中英

Invalid Column Name when accessing child table of parent c# entity framework

I am currently developing a web application which contains information about users and credit related information. I am using Asp.Net Identity to manage and handle the creation of user accounts within the web application and have several other tables which contain information directly related to the user.

I have set up a table (IdentityProfile) which is linked to the AspNetUsers table in the Identity framework. Each table is then connected to this table as a link to user account functionality within the application. Please see my ERD:

Entity Relationship Diagram Link

The IdentityProfile and UserProfile tables have the following referential constraint : UserProfile -> IdentityProfile based on the ProfileId primary key field in each table.

I am able to succesfully create an Identity Profile Record with a corresponding UserProfile Record:

public void CreateUserProfile(string title, string firstname, string lastname, DateTime dob, IdentityUser user)
    {         

        if(user != null) //Given the successfuly creation of a user account.
        {
            Guid profileId = user.Email.ConvertToMD5GUID();


            IdentityProfile identityProfile = new IdentityProfile //Manual Table Association Link (i.e. Between AspNetUsers Table and UserProfile Table).
            {
                Id = user.Id,
                ProfileId = profileId,
            };             

            identityProfile.UserProfile = new UserProfile
            {
                ProfileId = profileId,
                Title = title,
                FirstName = firstname,
                LastName = lastname,
                DOB = dob,
                DateRegistered = DateTime.Now,
                KBAFailed = false,
                CreditTrolleyRatingsRegistrationStatus = false,
                CreditActivityNotificationStatus = true,
                ThirdPartyPartnerNotificationStatus = true,
                CreditOffersNotificationStatus = true
            };

            ConsumerData.IdentityProfiles.Add(identityProfile);

            ConsumerData.SaveChanges();

        }

    }

However, when it comes to accessing the created UserProfile record, the Identity Profile returns null and a SqlException: Invalid column name 'UserProfile_ProfileId'. Invalid column name 'UserProfile_ProfileId'.

public void CreateCreditFootprint()
    {

        IdentityProfile identityProfile = ConsumerData
           .IdentityProfiles
           .Single(profile
           => profile.Id == CurrentUserId);

        //An issue with the way in which the user profile is instantiated. 

        identityProfile.UserProfile.CreditFootprint = new CreditFootprint  //ERROR OCCURS ON THIS LINE - SPECICIALLY on identityProfile.UserProfile returing null.

        {

            CreditReportId = identityProfile.UserProfile.LastName.ToString().ConvertToMD5GUID(),
            CreditScore = short.Parse(new Random().Next(500, 710).ToString()), //Example score.
            CreditScoreStatus = "Good", //Example status.
            CumulativeDebt = new Random().Next(1000, 10000), //Example debt.
            LastRetrieved = DateTime.Now,

        };

        ConsumerData.SaveChanges();

    }

    //Migrate method over to UserAccountLink class.
    public void CreateCreditApplicationProfile()
    {
        IdentityProfile identityProfile = ConsumerData
           .IdentityProfiles
           .SingleOrDefault(profile
           => profile.Id == CurrentUserId);

        identityProfile.UserProfile.CreditApplicationProfile = new CreditApplicationProfile {

            ApplicationProfileId = identityProfile.UserProfile.FirstName.ToString().ConvertToMD5GUID(),
            ApplicationCount = 0,
            ApplicationsAcceptedCount = 0,
            ApplicationsDeclinedCount = 0,
            PendingApplicationsCount = 0
        };

        ConsumerData.SaveChanges();
    }

All the records have been successfully created in the database tables (ie AspNetUsers, IdentityProfile (LINK) and UserProfile respectively). The exception is thrown when I locate an existing IdentityProfile record and try to access its UserProfile link - see line identityProfile.UserProfile.CreditApplicationProfile.

Any help would be greatly appreciated on this one.

Many Thanks,

Ben.

Here is my amended code:

public partial class IdentityProfile
{
    public string Id { get; set; }

    [Required]
    [ForeignKey("UserProfile")]
    public System.Guid ProfileId { get; set; }


    public virtual UserProfile UserProfile { get; set; }
}

public partial class UserProfile
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public UserProfile()
    {
        this.IdentityProfiles = new HashSet<IdentityProfile>();
    }

    public System.Guid ProfileId { get; set; }
    public string Title { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public System.DateTime DOB { get; set; }
    public System.DateTime DateRegistered { get; set; }
    public bool RegistrationStatus { get; set; }
    public bool KBAFailed { get; set; }
    public bool CreditActivityNotificationStatus { get; set; }
    public bool ThirdPartyPartnerNotificationStatus { get; set; }
    public bool CreditOffersNotificationStatus { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

    [InverseProperty("UserProfile")]
    public virtual ICollection<IdentityProfile> IdentityProfiles { get; set; }


    public virtual CreditApplicationProfile CreditApplicationProfile { get; set; }
    public virtual CreditFootprint CreditFootprint { get; set; }
}

Error After Update

Invalid Column Name Error example

At first, in order to load navigation properties you have to use .Include() and unless navigation properties are not included in your query, you will achieve NULL values.

Secondly, the error of Invalid column name 'UserProfile_ProfileId' is definitely related to your model and property mapping. You did not mention about your data model but any type of errors containing the message of "Invalid column name" is related to your mappings (primary of foreign keys).

In case of Entity Framework Code First, you can use the code blow based on your model

public class IdentityProfile 
{
   [Required]
   [ForeignKey("Profile")]
   public System.Guid ProfileId { get; set; }

   public virtual UserProfile Profile { get; set; }
}

public class UserProfile 
{
    [InverseProperty("Profile")]
    public virtual ICollection<IdentityProfile> IdentityProfiles { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM