Linq多对多关系矩阵(默认值为空)

时间:2018-11-16 04:42:24

标签: c# linq left-join associations

我正在尝试创建一个多对多关系的矩阵。但是,当关联表中没有创建记录时,我需要能够返回默认值(例如LEFT OUTER JOIN)。

例如,我有两个模型: MarketProfile和产品

public class MarketProfiles : BaseModel
{
    [Key]
    public int ProfileId { get; set; }

    [Required, StringLength(50)]
    public string Name { get; set; }
}

public class Offering : BaseModel
{
    public int OfferingId { get; set; }

    [Required, StringLength(50)]
    public string Name { get; set; }

    [Required, StringLength(20)]
    public string ShortName { get; set; }       
}

和关联模型Target:

public class Target
{
    [Key, Column(Order = 0)]
    public int OfferingId { get; set; }
    public virtual Offering Offering { get; set; }

    [Key, Column(Order = 1)]
    public int ProfileId { get; set; }
    [ForeignKey("ProfileId")]
    public virtual MarketProfiles Profile { get; set; }

    [Column(TypeName = "money")]
    public decimal? InitialSales { get; set; }

    [Column(TypeName = "money")]
    public decimal? AnnualSales { get; set; }
}

现在,一旦关联模型第一次被持久化,我希望能够创建一个表,其中MarketProfiles沿行向下移动,Professionals沿列移动。但是,我希望能够在未创建任何记录的情况下显示表格,因此我为InitialSales和AnnualSales字段提供了一个文本框,以输入值。

我可以使用以下查询(在关联表中有值的情况下)创建表

viewModel.Matrix = (from p in _repository.GetAll<MarketProfiles>()
                    join t in _repository.GetAll<Target>() on p.ProfileId equals t.ProfileId into ts
                     from targets in ts.DefaultIfEmpty()
                    join o in _repository.GetAll<Offering>() on targets.OfferingId equals o.OfferingId into off
                     from offs in off.DefaultIfEmpty()
                     group targets by p into g
                     select new MatrixViewModel
                     {
                          Name = g.Key.Name,
                          ProfileId = g.Key.ProfileId,
                          Targets = (from t in g
                                    select new TargetViewModel
                                    {
                                         AnnualSales = t.AnnualSales,
                                         InitialSales = t.InitialSales,
                                         OfferingId = t.OfferingId,
                                         OfferingName = t.Offering.ShortName
                                     }).ToList()
                      })

Linq甚至有可能吗?我可以使用动态Sql创建它,但是它太可怕了,我更喜欢使用Linq。

0 个答案:

没有答案