【问题标题】:How can I map a Foreign Key in EF Code First Fluent when the column name does not match the parent table?当列名与父表不匹配时,如何在 EF Code First Fluent 中映射外键?
【发布时间】: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


【解决方案1】:

主表中的外键和主键不必同名。将AssignedTo 映射到UserId 没问题。但是,您正在尝试定义 两个 关系,为此您还需要 两个 导航属性。您不能在两种关系中都使用UserProfile 作为导航属性,也不能两次使用Questions 集合。您可以像这样更改Question 实体(UserProfile 可以保持不变):

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 AssignedToUser { get; set; }
    public virtual UserProfile ModifiedByUser { get; set; }
}

然后创建这个映射:

this.HasRequired(t => t.AssignedToUser)
    .WithMany(t => t.Questions)
    .HasForeignKey(d => d.AssignedTo);

this.HasRequired(t => t.ModifiedByUser)
    .WithMany() // <- don't use "t => t.Questions" here again
    .HasForeignKey(d => d.ModifiedBy)
    .WillCasadeOnDelete(false);

必须为两个关系中的至少一个禁用级联删除。否则 SQL Server 将抱怨多个级联删除路径。

但是,这一切都可能无法解决您在创建外键约束时遇到的异常。此错误意味着UserProfile.UserId 不是UserProfile 表中的主键(或者通常它没有唯一约束)。也许UserId 只是复合主键的一部分(可能是UserId+UserName)?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多