我有以下2個類。我正在使用EF代碼與現有的數據庫。C# - 首先使用EF代碼獲取數據 - DbContext
public class Asset
{
[Key]
public decimal AssetId { get; set; }
[StringLength(20)]
public string AssetNumber { get; set; }
public decimal? DistrictId { get; set; }
public virtual District District { get; set; }
}
public class District
{
[Key]
public decimal? DistrictId { get; set; }
[StringLength(20)]
public string DistrictCode { get; set; }
[StringLength(255)]
public string Description { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
}
我需要得到資產的列表,其中DistrictId不爲空。
我使用下面的C#代碼:
IQueryable<CustomClass> assets = dbContext.Assets
.Where(a => a.DistrictId != null)
.Select(a => new CustomClass
{
});
我相信使用導航屬性,你並不需要明確聲言如下─其中(A => a.DistrictId = NULL )。我對此不確定。那麼你能否建議什麼是獲取DIstrictId不爲空的資產清單的更好方法。
感謝,
你試過:(!A => a.District = NULL) IQueryable的資產= dbContext.Assets 。凡 。選擇(A =>新CustomClass { }); 甚至只是:IQueryable的資產= dbContext.Assets 。凡(A => a.DistrictId.HasValue) 。選擇(A =>新CustomClass { }); ? –
HaukurHaf
我試過IQueryable assets = dbContext.Assets .Where(a => a.District!= null).Select(a => new CustomClass {}); - 這是工作。但不確定這是實現結果的最佳方式。 –
user659469
我不認爲有更好的方法。這是正確的。它怎麼能做得更簡單?我不認爲它可以。 – HaukurHaf