0

我需要发送到交接表生成的实体框架(CustomerEmployeeJobs)。每个工作都可以有多个客户员工。每个工作都必须有一个CustomerEmployee PM,CustomerEmployee Account,CustomerEmployee Admin和一个CustomerEmployee Superintendent.Right现在由CustomerEmployeeRole属性定义。当我创建一个新的工作时,我有选择框显示客户雇员,并有适当的标题。那么我怎么做这个POST?我认为这种关系将是多对多的。 Junction表有一个JobId和CustomerEmployeeId列。所以这似乎是正确的。我可以手动添加与多个CustomerEmployeeId相同的JobId。但是,我如何通过实际应用来做到这一点?这是新工作模式的一大特点。如果我改变了存储CustomerEmployee标题的方式会更好吗?相反, “串” Cu​​stomerEmployeeRole的可能是布尔值, “布尔” CustomerEmployeeIsPM,CustomerEmployeeIsAdmin等.... plunker如何在交接表中创建新记录

public class Job 
{ 
    //job 
    public int JobId { get; set; } 
    public int? JobNumber { get; set; } 
    public string JobName { get; set; } 

    public virtual ICollection<CustomerEmployee> CustomerEmployees { get; set; } 
} 
public class CustomerEmployee 
{ 
    [Key] 
    public int CustomerEmployeeId { get; set; } 
    public string CustomerEmployeeFirstName { get; set; } 
    public string CustomerEmployeeLastName { get; set; } 
    public string CustomerEmployeeRole { get; set; } 


    public virtual ICollection<Job> Jobs { get; set; } 
} 

// POST api/<controller> 
    public async Task<IHttpActionResult> PostnewJob([FromBody]JobViewModel newJob) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     using (var context = new ApplicationDbContext()) 
     { 
      var job = new Job(); 

      Mapper.CreateMap<JobViewModel, Job>(); 
      Mapper.Map(newJob, job); 

      context.Jobs.Add(job); 

      await context.SaveChangesAsync(); 

      return CreatedAtRoute("JobApi", new { job.JobId }, job); 
     } 
    } 

回答

2

我觉得你的模型是不正确的。你说的是:

  • 你的工作恰好有1 customerPM,准确地1 CustomerSuperintendent
  • 你CustomerPM可以有多个职位,以及你CustomerSuperintendent

所以你CustomerEmployee表和你之间的中作业表不需要联结表。你的工作表应该只是有2个外键的CustomerEmployee表

那么你的模型将是这样的,我想:

public class Job 
{ 
    //job 
    public int JobId { get; set; } 
    public int? JobNumber { get; set; } 
    public string JobName { get; set; } 

    [ForeignKey("CustomerPMId")] 
    public CustomerEmployee CustomerPM { get; set; } 
    [ForeignKey("CustomerSuperintendentId")]   
    public CustomerEmployee CustomerSuperintendent { get; set; } 
} 

而且allthough这不是你的问题的一部分,因此offtopic,但我想要提一下:使用automapper时要非常小心地使用它!另一方面是完美的,但从你的DTO到ef模型,IMO不要这样做!你的MVC模型可能会根据你视图中的不同需求而改变,然后你需要配置automapper来纠正哪些可能不值得麻烦,如果你保持你的实体好和小,就像你有自己的。

+0

它是如何知道这些是外键的?你可以请编辑我的帖子应该设置的方式。 – texas697 2014-10-19 21:20:34

+0

我不是一个风扇,也不是一个使用代码的实体框架的专家。不过,通常EF会根据您的导航属性自动找到您的外键。如果您有多个引用,就像现在一样,必须对其进行配置。请参阅此链接以获取文档:[EF Code First Conventions](http://msdn.microsoft.com/zh-cn/data/jj679962.aspx) – 2014-10-19 21:26:04

+0

它似乎与向导航属性添加DataAnnotations属性一样简单,在代码中查看我的编辑。 – 2014-10-19 21:29:31