我必须创建一个专门用于 JobOfferts 的控制器,或者在里面控制
客户控制器?
不一定,控制器和其他类一样应该遵循SRP(单一责任原则)。在这种情况下,只要 CustomerController 提供与 Customer 相关的信息就可以了。
当我尝试创建将表单提交到新 JobOffert 的视图时,我不知道如何将客户链接到这个新 JobOffert,如果我尝试使用客户模型创建页面,我没有 JobOffert 属性如果我使用 JobOffert 模型创建,我不知道如何在这两个对象之间建立联系。我该怎么做?
客户和 JobOffer 之间的链接是您定义的一对多,并且实体包含相互引用。例如。您可以通过查询 CustomerID = 1024 的 JobOffer 表来查找 ID 为 1024 的客户的所有 JobOffer。同样,每个 JobOffer 都可以通过实体类中的客户引用进行跟踪。
现在关于为客户创建新的 JobOffer,您可以这样做:
public class CustomerController : Controller
{
public CustomerBusiness customerBusiness { get; set; }
public CustomerController()
{
customerBusiness = new CustomerBusiness();
}
//Some code that makes CRUD and more these methods
[HttpGet]
public ActionResult ViewAllJobOffersForCustomer(int customerId)
{
ICollection<JobOfferModel> model = customerBusiness.GetAllJobOffersByCustomerId(customerId);
return View(model);
}
[HttpGet]
public ActionResult CreateJobOffer()
{
// Blank model object to accept values from user,
// you may like to create a view model based on UI needs.
JobOfferModel jobOfferModel = new JobOfferModel();
return View(jobOfferModel);
}
[HttpPost]
public ActionResult CreateJobOffer(JobOfferModel jobOffer)
{
// You get a filled object here that contains customer id and job offer details
customerBusiness.CreateJobOffer(jobOffer);
return RedirectToAction("ViewAllJobOffersForCustomer", new { customerId = jobOffer.CustomerId });
}
示例业务服务类:
public class CustomerBusiness
{
public ICollection<JobOfferModel> GetAllJobOffersByCustomerId(int customerId)
{
// TODO: Fetch job offer details from persistent store
// E.g.
// dataContext.JobOffers.Where(x => x.CustomerId == customerId).ToList();
throw new NotImplementedException();
}
public void CreateJobOffer(JobOfferModel jobOffer)
{
// TODO: Add job offer details in persistent store
// E.g.
// dataContext.JobOffers.Add(jobOffer);
}
}
修改实体类:
public class JobOfferModel
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
[Required]
[DefaultValue(false)]
public bool Acepted { get; set; }
[Required]
[DefaultValue(true)]
public bool Active { get; set; }
[Required]
[Column(TypeName = "DateTime2")]
public DateTime JobDate { get; set; }
[ForeignKey("Id")]
public int CustomerId { get; set; }
public virtual CustomerModel Customer { get; set; }
}
public class CustomerModel
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime BirthDate { get; set; }
public int PhoneNumber { get; set; }
public ICollection<JobOfferModel> JobOffert { get; set; }
}
所以基本上你将在 CustomerController 中有一个返回空 ViewModel 或 Model 对象的方法。在视图中,您将隐藏 customerId。因此,当表单发布时,它会与 JobOffer 详细信息一起映射到正确的客户。在 HttpPost 方法中拥有模型对象后,您只需在 JobOffer 表(任何持久存储)中插入一个条目,并关联 customerId。
还有其他细节,但我希望以上典型方法会给您一个良好的开端。干杯