0
我想問如何將多個模型對象映射到單個DTO。實體框架將多個模型投影到單個DTO
我有以下型號EF如下:
Bracket.cs
namespace MyApp.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Bracket")]
public partial class Bracket
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Bracket()
{
Teams = new HashSet<Team>();
}
public int BracketId { get; set; }
[Required]
[StringLength(50)]
public string BracketName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Team> Teams { get; set; }
}
}
Team.cs
namespace MyApp.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Team")]
public partial class Team
{
public int TeamId { get; set; }
[Required]
[StringLength(50)]
public string TeamName { get; set; }
public int BracketId { get; set; }
public virtual Bracket Bracket { get; set; }
}
}
我創建DTO對象來表示他們。
namespace MyApp.Models
{
public class BracketDto
{
public int BracketId { get; set; }
public string BracketName { get; set; }
public List<TeamDto> Teams { get; set; }
}
public class TeamDto
{
public int TeamId { get; set; }
public string TeamName { get; set; }
public int BracketId { get; set; }
}
}
在我的課之一,我用它來查詢數據庫和項目所產生的數據,這是我在做什麼:
public List<BracketDto> GetBrackets()
{
var brackets = (from a in this.Context.Brackets
join b in this.Context.Teams on a.BracketId equals b.BracketId
select new BracketDto()
{
BracketId = a.BracketId,
BracketName = a.BracketName
}).ToList<BracketDto>();
var teams = (from a in this.Context.Teams
select new TeamDto()
{
TeamId = a.TeamId,
TeamName = a.TeamName,
BracketId = a.BracketId
}).ToList<TeamDto>();
foreach(BracketDto bracket in brackets)
{
var tl = teams.Where(a => a.BracketId == bracket.BracketId).ToList();
bracket.Teams = tl;
}
var xtra = (from a in this.Context.Brackets
join b in this.Context.Teams on a.BracketId equals b.BracketId
select new BracketDto()
{
BracketId = a.BracketId,
BracketName = a.BracketName
}).ToList<BracketDto>();
return brackets;
}
當我得到的結果:
[
{
"BracketId": 1,
"BracketName": "Eastern Conference",
"Teams": [
{
"TeamId": 1,
"TeamName": "Indiana Pacers",
"BracketId": 1
},
{
"TeamId": 3,
"TeamName": "Cleveland Cavaliers",
"BracketId": 1
}
]
},
{
"BracketId": 2,
"BracketName": "Western Conference",
"Teams": [
{
"TeamId": 2,
"TeamName": "Los Angeles Lakers",
"BracketId": 2
},
{
"TeamId": 4,
"TeamName": "Los Angeles Clippers",
"BracketId": 2
}
]
}
]
我知道可能有更有效的方法來做到這一點。但我很不確定如何在LINQ查詢中完成它。
尋找意見和建議。謝謝!