[英]How do I Get Asp.net web api to join 2 tables (1 to many relation)
我是Web Api的新手,只是嘗試通過玩不同的例子來學習。 我完全堅持嘗試編寫Get請求以返回復雜類型。 我有3個實體,其中1個實體具有另一個實體的列表,所以我試圖弄清楚如何從兩個實體中返回數據。
我看了一些有關堆棧溢出的示例,這些示例表明使用了.include linq語句,但是當我嘗試這樣做時,卻遇到了編譯器錯誤(無法推斷出type參數。
基本上,我有一類球員,球隊和專長。 一旦完成這項工作,我就計划編寫一個有角度的項目。 特殊性表是給定玩家的多項選擇。
這是我到目前為止寫的
public class Player
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int JerseyNo { get; set; }
public DateTime DateAquired { get; set; }
public string Bio { get; set; }
[ForeignKey("TeamID")]
public virtual Team Team { get; set; }
public virtual IEnumerable<Specialty> Specialites { get; set; }
}
public class Specialty
{
public int Id { get; set; }
public string Speciality { get; set; }
public virtual Player Player { get; set; }
}
public class Team
{
public int Id { get; set; }
public string TeamName { get; set; }
public virtual Player Player { get; set; }
}
public class dbContext :DbContext
{
public DbSet<Player> Players { get; set; }
public DbSet<Team> Teams { get; set; }
public DbSet<Specialty> Specialties { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;Trusted_Connection=True;");
}
}
當我使用遷移創建數據庫時,它看起來像我想要的樣子,但是無法弄清楚Web Api的聯接是如何從我的專業表中獲取數據的。 .include無法識別我輸入為參數的任何值
private dbContext db = new dbContext();
// GET: api/values
[HttpGet]
public IEnumerable<Player> Get()
{
var teams = db.
Players
.Include("Specialties")
.Select(p=> new Player
看起來像這樣一個實體框架問題。
嘗試是否可以使其正常工作,以進行調試:
var teams = db.Players.ToList();
foreach (var player in teams)
{
// Force lazy loading of Specialities property
player.Specialities.ToList();
}
如果這不起作用,則似乎EF無法確定到數據庫的映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.