c#实体框架从嵌套对象返回列表
本文关键字:对象 返回 列表 嵌套 实体 框架 | 更新日期: 2023-09-27 18:09:33
如何利用Include()
从db
、WagonList
返回doc
?
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
document.Id = 73243;
document.Name = "SendingForm";
document.Wagons = new Wagons
{
Depos = "Main",
Id = 1,
Street = "WestSide",
WagonList = new List<Wagon>
{
new Wagon {Code="MP",Destination="China",Id=1,Number=90543 },
new Wagon { Code="MO",Destination="Bangkok",Id=2,Number=90543},
new Wagon {Code="MI",Destination="Burma",Id=3,Number=90543 }
}
};
using (var db = new SoccerContext())
{
//db.documents.Add(document);
//db.SaveChanges();
Document doc = db.documents.Include("Wagons").FirstOrDefault();
}
}
}
public class Document
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public Wagons Wagons { get; set; }
}
public class Wagons
{
[Key]
public int Id { get; set; }
public string Depos { get; set; }
public string Street { get; set; }
public List<Wagon> WagonList { get; set; }
}
public class Wagon
{
[Key]
public int Id { get; set; }
public string Code { get; set; }
public int Number { get; set; }
public string Destination { get; set; }
}
class SoccerContext : DbContext
{
public SoccerContext()
: base("DocumentDB")
{ }
public DbSet<Document> documents { get; set; }
}
}
对于single Document object
,它是直接的:
var wagonList = doc.Wagons.WagonList
对于List of Documents
,这样做(将使文档层次结构中的货车列表变平):
var wagonList = docList.SelectMany(doc => doc.Wagons.WagonList);