2016-09-01 33 views
0

我會盡力解釋這是我能做到的最好的,因此它是有道理的。將具有匹配屬性的兩個模型映射到新模型

我有兩個型號 - BuyerProfileProducerprofile

BuyerProfile

public class BuyerProfile : IAuditTrack 
{ 
    [KeyProperty(Identity = true)] 
    public int Id { get; set; } 
    [Required] 
    public string UserId { get; set; } 
    [Required] 
    public string Name { get; set; } 
    [Required] 
    public int BuyerTypeId { get; set; } 
    [Required] 
    public string Address { get; set; } 
    [Required] 
    public string City { get; set; } 
    [Required] 
    public string State { get; set; } 
    public string Zipcode { get; set; } 
    public string Description { get; set; } 

    [NonStored] 
    public string BuyerTypeDisplay { get; set; } 
} 

ProducerProfile

public class ProducerProfile : IAuditTrack 
{ 
    [KeyProperty(Identity = true)] 
    public int Id { get; set; } 
    [Required] 
    public string UserId { get; set; } 
    [Required] 
    public string Name { get; set; } 
    [Required] 
    public string Address { get; set; } 
    [Required] 
    public string City { get; set; } 
    [Required] 
    public string State { get; set; } 
    public string Zipcode { get; set; } 
    public string Description { get; set; } 
} 

我有我的控制器上的簡單方法檢索所有的配置文件在數據庫中和concatenates他們在一起。

[HttpGet] 
public JsonResult GetAllProfiles() 
{ 
    var buyerProfiles = _profileService.GetAllBuyerProfiles(); 
    var producerProfiles = _profileService.GetAllProducerProfiles(); 

    var profiles = buyerProfiles.Concat(producerProfiles); 

    return Json(profiles, JsonRequestBehavior.AllowGet); 
} 

現在我想要做的是能夠找到共享相同UserIdBuyerProfileProducerProfile在一起,將它們合併爲一個新的模式,應該是這樣的:

public class BuyerProducerprofile 
{ 
    public string UserId { get; set; } 
    public string BuyerName { get; set; } 
    public string ProducerName { get; set; } 
} 

的目前我正在構建的系統允許用戶完成1 BuyerProfile和1 ProducerProfile

因此,例如,在結果集中,我可能有一個BuyerProfile,包含以下信息:

  • 標識 - > 1543
  • 用戶ID - > ABC123
  • 名稱 - >鮑勃的購買公司

,幷包含以下信息的ProducerProfile

  • 標識 - > 1678
  • 用戶ID - > ABC123
  • 名稱 - >鮑勃的農產品公司

我希望能夠將兩者合併到我的新的模式,以便它看起來是這樣的:

  • 用戶ID - > ABC123
  • BUYERNAME - >鮑勃的購買公司
  • ProducerNam Ë - >鮑勃的農產品公司

我不知道這是不使用某種Nuget包,但是這將是真棒,如果我沒有使用一個,我不已經在所有可能的有。

我也正在使用AutoMapper做我的一些映射,但我找不到任何文檔顯示能夠使用它來做到這一點。

+0

你使用任何類型的框架來訪問你的數據庫?如實體框架? –

回答

1

你想要做的就是所謂的連接。你可以做這樣的

var buyerProfiles = _profileService.GetAllBuyerProfiles(); 
var producerProfiles = _profileService.GetAllProducerProfiles(); 

var combinedProfiles = 
    from bp in buyerProfiles 
    join pp in producerProfiles on bp.UserId equals pp.UserId 
    select new BuyerProducerprofile() 
    { 
     UserId = pp.UserId, 
     BuyerName = bp.Name, 
     ProducerName = pp.Name 
    } 

注:如果同一用戶可以有一個類型的配置文件的不止一個,這會返回一個結果買方的個人資料和生產分佈的每個組合可爲進行用戶。

其他注意事項:這就是所謂的「內部連接」,它只會爲擁有兩個配置文件的用戶提供結果。您也可以進行其他類型的連接,但這些連接的語法並不自然,我也沒有將它們用於記憶。我確定谷歌搜索可以找到你的語法。

+0

非常感謝您的支持!是的,我確實需要一個連接,它仍然會給我所有的配置文件,但只是'空'的值不匹配。我沒有意識到你可以做這樣的連接,儘管如此感謝一羣人在那裏指導我! – Quiver

相關問題