【问题标题】:Entity Framework Code First - redundant IDs实体框架代码优先 - 冗余 ID
【发布时间】:2014-05-11 17:28:06
【问题描述】:

如何去除多余的 ID?

我有一个用户配置文件模型 - 一个用户配置文件有一个连接模型列表。连接模型有一个用户配置文件(拥有该连接的用户配置文件)和一个用户配置文件2(用户配置文件连接到的另一个用户配置文件)。 在我的数据库连接表中,我得到以下列:

|身份证 |确认 |连接类型 | UserProfile_UserId | UserProfile2_UserId | UserProfile_UserId1 |

此处 UserProfile_UserId 将始终与 UserProfile_UserId1 相同。我真的很想摆脱那个额外的 ID 列。

public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<Connection> Connections { get; set; }
}

public class Connection
{
    [Key]
    public int Id { get; set; }
    public bool Confirmed { get; set; }
    public byte ConnectionType { get; set; }
    public virtual UserProfile UserProfile { get; set; }
    public virtual UserProfile UserProfile2 { get; set; }

}

任何帮助将不胜感激。

【问题讨论】:

    标签: entity-framework ef-code-first foreign-keys


    【解决方案1】:

    您是否尝试过像这样将属性添加到类中:

    public class Connection
    {
    [Key]
    public int Id { get; set; }
    public bool Confirmed { get; set; }
    public byte ConnectionType { get; set; }
    public int UserId {get; set;}
    public virtual UserProfile UserProfile { get; set; }
    public int UserId2 {get; set;}
    public virtual UserProfile UserProfile2 { get; set; }
    
    }
    

    【讨论】:

    • 感谢您的评论。是的,我试过了(还有很多其他的东西)。实际上(具有讽刺意味的是,刚刚发表这篇文章之后)我终于找到了解决方案。使用 InverseProperty 使其工作:
    • [InverseProperty("Connections")] public virtual UserProfile UserProfile { get;放; }
    • 您应该发布您的答案,以便将来帮助其他可能遇到同样问题的人。
    • 可以 - 但我要等到 8 小时后才能获准 :-)
    【解决方案2】:

    使用 InverseProperty 注解解决了这个问题: [逆属性(“连接”)] 公共虚拟用户配置文件用户配置文件 { 获取;放; }

    这在 InverseProperty 下进行了描述: http://msdn.microsoft.com/da-dk/data/jj591583.aspx#Relationships

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2016-07-08
      • 2011-08-05
      • 2017-09-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多