Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 当列名与父表不匹配时,如何在EF Code First Fluent中映射外键?_Sql_Sql Server_Sql Server 2008_Entity Framework_Entity Framework 4 - Fatal编程技术网

Sql 当列名与父表不匹配时,如何在EF Code First Fluent中映射外键?

Sql 当列名与父表不匹配时,如何在EF Code First Fluent中映射外键?,sql,sql-server,sql-server-2008,entity-framework,entity-framework-4,Sql,Sql Server,Sql Server 2008,Entity Framework,Entity Framework 4,我想使用fluentapi进行映射。我看到了一些其他的例子,但是这些看起来和我想做的不同 以下是我的SQL: ALTER TABLE [Question] ADD CONSTRAINT [FK_QuestionUserProfile] FOREIGN KEY([AssignedTo]) REFERENCES [UserProfile] ([UserId]) 这给了我这个错误信息: There are no primary or candidate keys in the referenced

我想使用fluentapi进行映射。我看到了一些其他的例子,但是这些看起来和我想做的不同

以下是我的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; }
}
但是,当ForeignKey在UserProfile中指定了to作为所讨论的名称和UserId时,这会起作用吗。是
在映射中有一种方法可以指定它们应该映射到UserId?

主体表中的外键和主键不必具有相同的名称。将
分配给
映射到
用户ID
没有问题。然而,您正试图定义两个关系,要做到这一点,您还需要两个导航属性。您不能在这两种关系中将
UserProfile
用作导航属性,也不能将
Questions
集合使用两次。您可以像这样更改您的
问题
实体(
UserProfile
可以保持不变):

公开课问题
{
public int QuestionId{get;set;}
公共字符串文本{get;set;}
分配给{get;set;}的公共int
公共int被{get;set;}修改
公共虚拟用户配置文件AssignedToUser{get;set;}
公共虚拟用户配置文件ModifiedByUser{get;set;}
}
然后创建此映射:

this.HasRequired(t=>t.AssignedToUser)
.有很多(t=>t个问题)
.HasForeignKey(d=>d.AssignedTo);
this.HasRequired(t=>t.ModifiedByUser)

.WithMany()//您的用户ID是否在fluent configs中标记为UserProfile的主键?是的,它是主键
        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);