我有两个POCO条款清单和电子书详情
如何将数据检索为Inventory to =>很多很多
public class Inventory
{
// This determine the One to Many RelationShip
public Inventory()
{
this.Lots = new HashSet<Lot>();
}
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required]
public string ItemID { get; set; }
public string Description { get; set; }
public Nullable<DateTime> CreateDate { get; set; }
public string CreateUser { get; set; }
public decimal LastCost { get; set; }
public bool MonitorLevel { get; set; }
public short MinLevel { get; set; }
public short MaxLevel { get; set; }
public string GTIN { get; set; }
public decimal Weight { get; set; }
public string UOM { get; set; }
// Navigation Property
public virtual ICollection<Lot> Lots { get; set; }
}
public class Lot
{
public int Id { get; set; }
public Nullable<DateTime> CreateDate { get; set; }
public string CreateUser { get; set; }
public Nullable<DateTime> ExpDate { get; set; }
public string LotSerial { get; set; }
public virtual Inventory Inventory { get; set; }
}
我试试这个,但转换类型有错误
public class InventoryController : ApiController
{
private FarmStoreContext db = new FarmStoreContext();
// Project Inventory to inventory DTOs.
private IQueryable<InventoryDTO> MapInventories()
{
return from i in db.Inventories
select new InventoryDTO() { Id = i.Id, Description = i.Description, ItemID = i.ItemID, GTIN = i.GTIN, LastCost = i.LastCost, Weight = i.Weight, UOM = i.UOM};
}
public IEnumerable<InventoryDTO> GetInventories()
{
return MapInventories().AsEnumerable();
}
public InventoryDTO GetInventory(int Id)
{
Inventory inventory = db.Inventories;// <== Error - Here can not implicity convert type System.Data.Entiry.Dbset<....Models.Inventory> To ....Models.Inventory
//var inventory = (from i in MapInventories()
// where i.Id == Id
// select i).FirstOrDefault();
if (inventory == null)
{
throw new HttpResponseException(
Request.CreateResponse(HttpStatusCode.NotFound));
}
return new InventoryDTO()
{
DetaislLots = from d in inventory.Lots
select new InventoryDTO.DetaislLot()
{
LotSerial = d.LotSerial,
LIFOdate = d.LIFOdate,
QtyOriginal = d.QtyOriginal,
QtyAllocated = d.QtyAllocated,
QtyOnHand = d.QtyOnHand,
QtyAvailable = d.QtyAvailable,
Status = d.Status,
LineComment = d.LineComment,
UnitCost = d.UnitCost,
ReceiptDate = d.ReceiptDate
}
};
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
答案 0 :(得分:1)
db.Inventories
是一个DbSet<Inventory>
,它是一个集合,而您期待一个Inventory
。您必须执行返回单个Inventory
的查询。尝试:
Inventory inventory = db.Inventories.FirstOrDefault(i => i.Id == Id);
您在该行下方的评论中基本上都有此查询。您可以使用Lots
上的导航属性Inventory
来获取相关的Lot
个对象:
List<Lot> lots = inventory.Lots.ToList();