我有两个类,User 和 Follow,我创建了与同一个类的两个关系,但我需要限制这对外键的唯一性。
我尝试添加索引,但它不起作用,索引没有添加到迁移代码中,我认为这是因为 User 和 FollowUser 是虚拟的。
如何在一对虚拟外键上添加唯一性?
提前致谢。
注意:我使用 Azure 移动应用服务,主键字段会自动添加。
public class Following : EntityData
{
[Index("IX_FriendshipUniqueness", 1, IsUnique = true)]
public virtual User User { get; set; }
[Index("IX_FriendshipUniqueness", 2, IsUnique = true)]
public virtual User FollowingUser { get; set; }
[StringLength(10)]
public string Status { get; set; }
}
public class User : EntityData
{
public User()
{
this.Followings = new HashSet<Following>();
this.Followers = new HashSet<Following>();
}
[InverseProperty("User")]
public virtual ICollection<Following> Followings { get; set; }
[InverseProperty("FollowingUser")]
public virtual ICollection<Following> Followers { get; set; }
}
最佳答案
请阅读我几天前撰写的关系建议专栏 - 它有助于了解如何限制 Azure 移动应用程序请求:https://shellmonger.com/2016/05/27/30-days-of-zumo-v2-azure-mobile-apps-day-26-relationship-advice/
简短版本 - 尽管 EF6 允许此类约束(我并不是说它允许 - 我对 EF 不感兴趣,无法做出明确的声明),但 Azure 移动应用程序不提供执行这些约束的能力。它需要在您的客户端代码中强制执行。
关于entity-framework - 如何使用 Entity Framework 代码优先在虚拟列上添加索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494432/