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

相關問題