将具有匹配 属性 的两个模型映射到一个新模型

Map two models with a matching property to a new model

我会尽我所能解释这一点,以便它有意义。

我有两个模型 - BuyerProfileProducerprofile

买家资料

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);
}

现在我想做的是能够找到共享相同 UserId 的每个 BuyerProfileProducerProfile 并将它们合并到一个看起来像的新模型中这个:

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

我正在构建的当前系统只允许用户完成 1 BuyerProfile 和 1 ProducerProfile

例如,在结果集中我可能有一个 BuyerProfile 包含以下信息:

和包含以下信息的 ProducerProfile

我希望能够将两者结合到我的新模型中,使其看起来像这样:

如果不使用某种 Nuget 包,我不确定这是否完全可行,但如果我不必使用我还没有的包,那就太棒了。

我目前也在使用 AutoMapper 来做一些映射,但我找不到任何说明可以使用它来做这件事的文档。

您想要做的事情称为联接。你可以这样做

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 
    }

注意:如果同一个用户可以拥有不止一种类型的个人资料,这将 return 可以为该用户制作的买方个人资料和生产者个人资料的每种组合的结果。

其他注意事项:这就是所谓的 "inner join",它只会为您提供具有两种配置文件的用户的结果。您也可以执行其他类型的连接,但这些连接的语法感觉不是很自然,而且我没有让它们记住。我相信 google 搜索可以找到适合您的语法。