【问题标题】:Add column to another table and return as a List C#将列添加到另一个表并作为列表返回 C#
【发布时间】:2017-12-08 22:40:55
【问题描述】:

我有表格:ma​​in_datauser_data

ma​​in_data 具有表 user_data 的外键 user_id


我想返回一个列表,其中包含 ma​​in_data 表中的所有列以及 user_data 表中的 full_name 列。

我已经尝试过这样做,但不幸的是我的代码不起作用。

public override IList<main_data> GetAllDetached()
{
    return this.context.main_data.Join(this.context.user_data, 
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();
}

出现以下错误:

不能隐式转换类型'System.Collections.Generic.List 匿名类型:十进制user_id,字符串full_name' 'System.Collections.Generic.IList ProjectName.Model.main_data'。一个 存在显式转换(您是否缺少演员表?)

【问题讨论】:

  • 定义“不起作用”。
  • it doesn't work?的定义是什么

标签: c# mysql database list return


【解决方案1】:

创建一个 DTO 类,其中包含要返回到结果中的两个表中的属性:

 Class FinalResult
{
 public int user_id {get; set;}
 public string full_name {get; set;}
 }

然后在你的代码中:

 public override List<FinalResult> GetAllDetached()
{

    var result = this.context.main_data.Join(this.context.user_data, 
    o => o.user_id, i => i.user_data_id, (ud, fullName) => new {
    ud.user_id, fullName.full_name }).ToList();

 var finalResult = result.Select(x => new FinalResult()
        {
            user_id = x.user_id ,
            full_name = x.full_name 

        }).ToList();
        return finalResult ;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2021-08-18
    • 2016-04-10
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多