【问题标题】:Two same class types in entity framework class issue实体框架类问题中的两个相同的类类型
【发布时间】:2012-07-01 15:30:57
【问题描述】:

我正在实现允许用户互相关注的功能。 我有数据库表:

User{UserId, FirstName, LastName etc.}
Followings{FollowerUserId, FollowingUserId, CreatedOnDate etc.}

所以我添加了 EF 类:

public class Follow
    {
        [Key, Column(Order = 1)]
        public Guid FollowerUserId { get; set; }
        [Key, Column(Order = 2)]
        public Guid FollowUserId { get; set; }        
        public DateTime CreatedOnDate { get; set; }

        public virtual User Follower { get; set; }
        public virtual User Following { get; set; }
    }

最后两个虚拟属性会导致问题。 当我打电话时:

var model = con.Follows.Where(x => x.FollowerUserId == uid);

我得到以下异常:

Invalid column name 'Following_UserId'.

这个问题可能是因为一个类中有两个 User 对象。知道如何解决这个问题吗?
更新

public class User
    {

        public Guid UserId { get; set; }
        ...
        public virtual ICollection<Follow> Following { get; set; }
        public virtual ICollection<Follow> Followers { get; set; }
    }

【问题讨论】:

  • userID和navigation属性我好像不合适,你应该只放其中一个,否则EF无法建立它们之间的连接
  • 你能解释得更好吗?我不确定如何解决这个问题?

标签: c# entity-framework entity-framework-4.1


【解决方案1】:

我认为原因是外键属性(FollowerUserIdFollowUserId)和导航属性(FollowerFollowing)不遵守命名约定,因此 EF 无法识别第一个属性作为外键。您可以通过使用 [ForeignKey] 属性显式指定 FK 属性来解决此问题:

public class Follow
{
    [Key, Column(Order = 1), ForeignKey("Follower")]
    public Guid FollowerUserId { get; set; }
    [Key, Column(Order = 2), ForeignKey("Following")]
    public Guid FollowUserId { get; set; }        

    public DateTime CreatedOnDate { get; set; }

    public virtual User Follower { get; set; }
    public virtual User Following { get; set; }
}

编辑

至少第二个属性不遵守命名约定,第一个看起来不错。因此,或者您可以通过将第二个 FK 属性 FollowUserId 重命名为:

public Guid FollowingUserId { get; set; }        

...因为导航属性被称为Following

编辑 2

关于您的更新:您需要添加 [InverseProperty] 属性来告诉 EF 哪些导航属性属于一起:

public class Follow
{
    [Key, Column(Order = 1), ForeignKey("Follower")]
    public Guid FollowerUserId { get; set; }
    [Key, Column(Order = 2), ForeignKey("Following")]
    public Guid FollowUserId { get; set; }        

    public DateTime CreatedOnDate { get; set; }

    [InverseProperty("Followers")]  // refers to Followers in class User
    public virtual User Follower { get; set; }
    [InverseProperty("Following")]  // refers to Following in class User
    public virtual User Following { get; set; }
}

【讨论】:

  • 感谢这解决了我在后续课程中的问题。如果这不是问题,还有一件事我还尝试将追随者/追随者的集合添加到用户类(我在我的问题更新中添加了它)并且我再次收到类似的错误:无效的列名'User_UserId'。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多