【发布时间】:2016-08-29 06:26:34
【问题描述】:
我有一个职位模型,我正在尝试将可选的职位调查添加到:
public class Job
{
[Key]
public int JobID { get; set; }
// Leaving out all the other fields...
public virtual JobSurvey JobSurvey { get; set; }
}
工作调查模型如下所示:
public class JobSurvey
{
[Key]
public int JobSurveyId { get; set; }
public string CustomerEmail { get; set; }
[Index]
[Column(TypeName = "Date")]
public DateTime? SentDate { get; set; }
[Column(TypeName = "Date")]
public DateTime? ReturnedDate { get; set; }
public int? RatingValue { get; set; }
public virtual Job Job { get; set; }
}
在我的上下文中,我添加了以下内容:
modelBuilder.Entity<Job>()
.HasOptional(s => s.JobSurvey)
.WithRequired(j => j.Job);
当我运行 add-migration 时,脚本创建了以下内容:
CreateTable(
"dbo.JobSurveys",
c => new
{
JobSurveyId = c.Int(nullable: false),
CustomerEmail = c.String(nullable: false, maxLength: 100),
SentDate = c.DateTime(storeType: "date"),
RatingValue = c.Int(),
})
.PrimaryKey(t => t.JobSurveyId)
.ForeignKey("dbo.Jobs", t => t.JobSurveyId)
我的问题是创建的表没有能够转到相关实体的外键属性。
因此,在我的 SQL 中,没有 JobSurveyId 属性可以让我获取工作调查,并且我的 JobSurvey 表没有返回到工作的导航属性。所以我可以创建 JobSurveys,但它们没有关联。
我做错了什么?
编辑
我尝试如下修改 JobSurvey:
[Key]
[ForeignKey("Job")]
public int JobSurveyId { get; set; }
public int JobId { get; set; }
没有成功
编辑 2
还尝试将 [Required] 添加到导航属性,但 add-migration 并未将此视为需要更新的更改:
[Required]
public virtual Job Job { get; set; }
【问题讨论】:
-
İ 认为您没有正确显示您的
Job课程。您在模型内初始化上下文?在构造函数中声明属性? -
不,我没有在 Job 构造函数中初始化 jobsurvey 属性(因为 JobSurvey 可以为 null)
-
请在问题中更正您的
Job类 -
我的工作班出了什么问题?什么修正?你有所有相关的属性吗?
-
对不起,我明白你的意思了,我更新了问题
标签: c# asp.net-mvc entity-framework