我想给一个表添加一个外键。我已经添加了所需的列,但是当我尝试使用 PostMan 将值传递到表中时出现错误。
这是我的
JobPosting
实体/表:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Backend.Model
{
public class JobPosting
{
[Key]
public int JobId { get; set; }
[ForeignKey("HR")]
public int? HrId { get; set; }
public virtual HrRegistration HR{ get; set; }
public string Title { get; set; }
public int Experience { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public int Ctc { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
}
}
这是我的
HRRegistration
实体:
using System.ComponentModel.DataAnnotations;
namespace Backend.Model
{
public class HrRegistration
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string Mobile { get; set; }
public string Email { get; set; }
public string Company { get; set; }
public string Post { get; set; }
public string CTC { get; set; }
public DateTime CreatedDate { get; set; }
}
}
这是我用来将数据插入表中的方法
[AllowAnonymous]
[HttpPost("InsertJobDetails")]
public IActionResult InsertJobDetails(JobPosting job)
{
job.CreatedDate = DateTime.Now;
Context.jobPostings.Add(job);
Context.SaveChanges();
return Ok(job);
}
下面是我得到的错误
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-f3dbe55093c2de02f7258fc88dc11a4f-d9264da1a2769bd3-00",
"errors": {
"HR": [
"The HR field is required."
]
}
}
这里是错误的截图:
[ForeignKey("HrId")]
属性告诉 Entity Framework HrId
属性是 HrRegistration
表的外键。默认情况下,实体框架使用约定 [TableName]Id
作为外键。
但是,在这种情况下,外键属性被命名为
HrId
而不是HrRegistrationId
,因此您需要使用[ForeignKey]
属性来显式指定外键属性。
public int? HrId { get; set; }
[ForeignKey("HrId")]
public virtual HrRegistration HR{ get; set; }