【发布时间】:2013-08-05 01:53:37
【问题描述】:
我想使用 Fluent API 进行映射。我看到了其他一些例子,但这些看起来与我想做的不同。
这是我的 SQL:
ALTER TABLE [Question] ADD CONSTRAINT [FK_QuestionUserProfile]
FOREIGN KEY([AssignedTo]) REFERENCES [UserProfile] ([UserId])
这给了我这个错误信息:
There are no primary or candidate keys in the referenced table 'UserProfile'
that match the referencing column list in the foreign key 'FK_QuestionUserProfile'
Could not create constraint
我有两个班级:
public class Question
{
public int QuestionId { get; set; }
public string Text { get; set; }
public int AssignedTo { get; set; }
public int ModifiedBy { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
public partial class UserProfile
{
public UserProfile()
{
this.webpages_Roles = new List<webpages_Roles>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
我想在 Question UserProfile 之间进行映射,以便:
- AssignedTo 映射到 UserProfile 中的 UserId。
- Modified 映射到 UserProfile 中的 UserId。
到目前为止,我的 QuestionMap 中有这个
this.HasRequired(t => t.UserProfile)
.WithMany(t => t.Questions)
.HasForeignKey(d => d.AssignedTo);
this.HasRequired(t => t.UserProfile)
.WithMany(t => t.Questions)
.HasForeignKey(d => d.ModifiedBy);
但这是否会起作用,因为 ForeignKey 已将 AssignedTo 作为 Question 中的名称和 UserProfile 中的 UserId。是 映射中有一种方法可以指定它们应该映射到 UserId 吗?
【问题讨论】:
-
您的 UserId 是否在 Fluent 配置中标记为 UserProfile 的主键?
-
是的,它是主键
标签: sql sql-server sql-server-2008 entity-framework entity-framework-4