111*_*110 5 c# entity-framework entity-framework-4.1
我正在实现允许用户互相关注的功能.我有数据库表:
User{UserId, FirstName, LastName etc.}
Followings{FollowerUserId, FollowingUserId, CreatedOnDate etc.}
Run Code Online (Sandbox Code Playgroud)
所以我添加了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; }
}
Run Code Online (Sandbox Code Playgroud)
最后两个虚拟属性问题.我打电话的时候:
var model = con.Follows.Where(x => x.FollowerUserId == uid);
Run Code Online (Sandbox Code Playgroud)
我得到以下异常:
Invalid column name 'Following_UserId'.
Run Code Online (Sandbox Code Playgroud)
该问题可能是由于一个类中有两个User对象引起的.知道如何解决这个问题吗?
UPDATE
public class User
{
public Guid UserId { get; set; }
...
public virtual ICollection<Follow> Following { get; set; }
public virtual ICollection<Follow> Followers { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我认为原因是外键属性 (FollowerUserId和FollowUserId) 和导航属性 (Follower和Following) 不遵守命名约定,因此 EF 无法将第一个属性识别为外键。您可以通过使用以下属性显式指定 FK 属性来解决该问题[ForeignKey]:
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; }
}
Run Code Online (Sandbox Code Playgroud)
编辑
至少第二个属性不遵守命名约定,第一个属性看起来不错。因此,您也可以通过将第二个 FK 属性重命名为来解决该问题FollowUserId:
public Guid FollowingUserId { get; set; }
Run Code Online (Sandbox Code Playgroud)
...因为导航属性被称为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; }
}
Run Code Online (Sandbox Code Playgroud)