使用Entity Framework获取外键记录并在Angular中显示

时间:2019-03-15 11:38:13

标签: c# entity-framework-6

我在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较陌生,我无法弄清楚如何准确获取每个广告资源的所有本地化信息

1 个答案:

答案 0 :(得分:2)

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 
   });