我建立了一个具有ef核心代码优先管理的数据库。我有两个相关的表,我想把数据插入到一个表中。但是由于它与另一个表有关系,所以它试图将数据抛到另一个表中。而我只想记录一张桌子。我该怎么做?
代码:
public class JobTable
{
[Key]
public int ID_JOB { get; set; }
public JobType JobType { get; set; }
public string JOB_KEY { get; set; }
public TimeSpan JOB_TIME { get; set; }
public int? DAY { get; set; }
public Boolean IS_ACTIVE { get; set; }
public string? DESCRIPTION { get; set; }
public CustomUser CustomUser { get; set; }
}
public class JobType
{
[Key]
public int ID_JOB_TYPE { get; set; }
public string JOB_TYPE_NAME { get; set; }
public List<JobTable> jobTable { get; set; }
}
ef代码:
context.JobTable.Add(jobTable);
context.SaveChanges();
我只想把数据添加到“就业”表中。但它也尝试将数据抛到“jobtype”表中,因为它与“jobtype”表相关。我不想要这个。我该怎么做呢?
发布于 2022-11-26 09:12:34
在插入JobTable
记录时,定义JobType
的当前方法还将为JobTable
创建一个新记录。
相反,修改JobTable
以应用外键属性(JobTypeId
)来定义与JobType
表的关系。
public class JobTable
{
...
public int JobTypeId { get; set; }
public virtual JobType JobType { get; set; }
}
public class JobType
{
...
public ICollection<JobTable> JobTables { get; set; }
}
在插入新的JobTable
记录时,需要将JobType
的Id
提供到要插入的实体数据中。
参考
https://stackoverflow.com/questions/74580826
复制相似问题