![](/img/trans.png)
[英]Get records via foreign key in another table in Entity Framework 6
[英]Get foreign key records using Entity Framework and display in Angular
我在EF中使用數據庫優先方法,因此一切都生成了,並創建了一個Inventory
模型類:
public class InventoryModel
{
public int InventoryID {get;set;}
public string Employee { get; set; }
public string Warehouse { get; set; }
public byte Status { get; set; }
public DateTime Date { get; set; }
public ICollection<Localization> Localization { get; set; }
}
這是生成的實體
public partial class xInventory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public xInventory()
{
this.xLocalization = new HashSet<xLocalization>();
}
public int InventoryID { get; set; }
public int Employee { get; set; }
public byte Warehouse { get; set; }
public byte Status { get; set; }
public System.DateTime Date{ get; set; }
public virtual xWarehouse xWarehouse { get; set; }
public virtual xEmployee xEmployee { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<xLocalization> xLocalization { get; set; }
}
這是我沒有本地化的GET
// GET api/<controller>
public IEnumerable<InventarioModel> Get()
{
InventoryContext db = new InventoryContext();
var query = db.xInventory
.Select(i => new InventoryModel
{
InventoryID = i.InventoryID,
Employee = i.xEmployee.Employee,
Warehouse = i.xWarehouse.Warehouse,
Status = i.Status,
Date = i.Date
});
return query;
}
這是我嘗試獲取本地化版本的嘗試
// GET api/<controller>
public IEnumerable<InventarioModel> Get()
{
InventoryContext db = new InventoryContext();
var query = db.xInventory
.Select(i => new InventoryModel
{
InventoryID = i.InventoryID,
Employee = i.xEmployee.Employee,
Localization= i.xLocalization.Any(l => l.InventoryID == i.InventoryID)
Warehouse = i.xWarehouse.Warehouse,
Status = i.Status,
Date = i.Date
});
return query;
}
但是,這會導致錯誤“無法將類型轉換為布爾值”,並且由於我對linq較陌生,因此我無法弄清楚如何准確獲取每個廣告資源的所有本地化信息
Any
方法返回的bool
顯然不適合ICollection<Localization>
。 如果您需要獲得過濾的本地化信息,請使用Where
var query = db.xInventory
.Select(i => new InventoryModel
{
InventoryID = i.InventoryID,
Employee = i.xEmployee.Employee,
Localization = i.xLocalization.Where(l => l.InventoryID == i.InventoryID).Tolist()
Warehouse = i.xWarehouse.Warehouse,
Status = i.Status,
Date = i.Date
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.