【问题标题】:Invalid Column Name when accessing child table of parent c# entity framework访问父c#实体框架的子表时列名无效
【发布时间】:2019-07-03 10:39:15
【问题描述】:

我目前正在开发一个包含用户信息和信用相关信息的网络应用程序。我正在使用 Asp.Net Identity 来管理和处理 Web 应用程序中用户帐户的创建,并且还有其他几个包含与用户直接相关的信息的表。

我已经设置了一个表 (IdentityProfile),它链接到 Identity 框架中的 AspNetUsers 表。然后每个表都连接到该表,作为应用程序内用户帐户功能的链接。请查看我的 ERD:

Entity Relationship Diagram Link

IdentityProfile 和 UserProfile 表具有以下引用约束:UserProfile -> IdentityProfile 基于每个表中的 ProfileId 主键字段。

我能够成功创建具有相应用户配置文件记录的身份配置文件记录:

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();

        }

    }

但是,在访问创建的 UserProfile 记录时,身份配置文件返回 null 和 SqlException: Invalid column name 'UserProfile_ProfileId'。列名“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();
    }

所有记录均已在数据库表中成功创建(即分别为 AspNetUsers、IdentityProfile (LINK) 和 UserProfile)。当我找到现有的 IdentityProfile 记录并尝试访问其 UserProfile 链接时引发异常 - 请参阅行 identityProfile.UserProfile.CreditApplicationProfile。

任何帮助将不胜感激。

非常感谢,

本。

这是我修改后的代码:

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; }
}

更新后出错

Invalid Column Name Error example

【问题讨论】:

  • 在这种情况下,EF 不理解IdentityProfile 实体上的ProfileIdProfileId 模型上ProfileId 的外键。因此,它正在组成它认为应该存在于IdentityProfile 表中的列 (UserProfile_ProfileId),以便它能够找到正确的UserProfile。不幸的是,我的 EF 知识有点萎缩,但这是真正的根本原因,解决方案将是修复您的映射属性,以明确 IdentityProfile.ProfileIdUserProfile.ProfileId 的外键。

标签: c# sql asp.net entity-framework asp.net-identity


【解决方案1】:

首先,为了加载导航属性,您必须使用.Include(),除非您的查询中不包含导航属性,否则您将获得 NULL 值。

其次,Invalid column name 'UserProfile_ProfileId'的错误肯定和你的模型和属性映射有关。您没有提及您的数据模型,但包含“无效列名”消息的任何类型的错误都与您的映射(外键的主键)有关。

在实体框架代码优先的情况下,您可以根据您的模型使用代码打击

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; }
}

【讨论】:

  • 感谢您的回复。我已经添加了相关的数据模型并使用您的代码更新了它们。如果有帮助,IdentityProfile(M) 和 UserProfile(1) 表之间存在多对一(强制)关系。
  • 你为什么把 InverseProperty 放在你的上下文中!! => [InverseProperty("ProfileId")]public virtual DbSet UserProfiles { get;放; } 。您必须在模型中定义导航
  • 1.您必须从 context 中删除 [InverseProperty("ProfileId")]。 2. 在您的 UserProfile 类中,您必须定义正确的名称。问题在于您的导航名称。尝试使用上面给定的示例再次检查名称
  • 我已经更新了 UserProfile 数据模型类,但仍然遇到同样的错误。
  • 我更新了我的示例代码。请重新检查您的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多