0

I would like to do mapping using the Fluent API. I saw some other examples but these look different to what I want to do.

Here is my SQL:

ALTER TABLE [Question] ADD CONSTRAINT [FK_QuestionUserProfile] 
FOREIGN KEY([AssignedTo]) REFERENCES [UserProfile] ([UserId])

Which gives me this error message:

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

I have two classes:

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; }
}

I want to do the mapping between Question <> UserProfile so that:

  • AssignedTo is mapped to UserId in UserProfile.
  • Modified is mapped to UserId in UserProfile.

I have this so far in my 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);

But will this work as the ForeignKey has AssignedTo as the name in Question and UserId in UserProfile. Is there a way in the mappings that I can specify they should map to UserId ?

4

1 回答 1

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)?

于 2013-08-04T20:41:44.340 回答