我在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;
}
然而,这会导致错误“无法将类型转换为bool”,我无法弄清楚如何准确获取每个库存的所有本地化,因为我对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
});