c# - Entity Framework 类问题中的两个相同类类型

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

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

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'.

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

public class User
    {

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

最佳答案

我认为原因是外键属性(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; }
}

关于c# - Entity Framework 类问题中的两个相同类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11272990/

相关文章:

.net - 通过 Entity Framework 的 Sql Server Freetext

c# - 如何查询带有特定枚举标志的对象,使用 db int 来存储它

c# - 在 Entity Framework 中调用存储过程时的字符串准备

entity-framework-4.1 - 如何使用测试数据轻松填充 Entity Framework 上下文初始值设定项?

c# - SQL 事务 - SQL Server 还是 C#?

c# - 带有autofac的开放通用条件注册装饰器

entity-framework - SQL Server 2008 R2 中的时间数据类型是否支持 MVC4 的 Entityframework

c# - Entity Framework 。多个 DbContext 多个数据库。 MySQL。代码优先

c# - 如何使用 itextsharp 库旋转 pdf

c# - 在 BackgroundWorker 中等待下载完成