加入LINQ to SQL列表(SQL模式)

时间:2017-10-01 10:49:29

标签: c# entity-framework

我有表新闻:

public class New
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }
}

并且每个新人都有一个民意调查,并将其保存在表NewOptions:

public class NewOption
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [ForeignKey("New")]
    public int NewId { get; set; }

    [Required]
    public string Option { get; set; }

    public virtual New New { get; set; }
}

新闻1:M NewOptions 以及他们各自的DTO。我想通过各自的选择获得最新消息:

var news =
    from theNew in this.context.News
    join option in this.context.NewOptions on theNew.Id equals option.NewId
    select new NewDto
    {
        Id = theNew.Id,
        Title = theNew.Title,
        Options = new NewOptionDto
        {
            Id = option.Id,
            Option = option.Option
        }
    };

错误是:无法将NewOptionDto类型转换为IEnumerable

1 个答案:

答案 0 :(得分:0)

尝试这样的代码。我不确定我是否100%得到它,但它很接近。您的新类需要NewOption的属性才能使下面的代码生效。

var news =
    (from theNew in this.context.News
    join option in this.context.NewOptions on theNew.Id equals option.NewId
    select new {theNew = theNew, option = option}).Select(x =>  new NewDto() {
        Id = x.theNew.Id,
        Title = x.theNew.Title,
        Options = x.option.Select(y => new NewOptionDto() {
            Id = y.Id,
            Option = y.Option
        }).ToList()
    }).ToList();