我有 2 個 SQL 表,它們是通過 SQL Server Managment Studio(包括 PK 和 FK)創建的:
sql 表
在 Visual Studio 的 WinForm 專案中,我通過Code First 將資料模型添加到現有資料庫中,并通過以下 linq-query 讀取資料:
dataGridView1.DataSource = dbContext.deliveries.OrderBy(d => d.id).ToList();
現在 datagridView1 由表“deliveries”中的列組成,但不是顯示列customer_id ,而是顯示客戶的相應名稱和地址。
stackoverflow 上的其他一些答案建議編輯查詢并使用“包含”屬性。所以我嘗試使用
deliveries.Include(d=>d.customer.name).OrderBy(d => d.id).ToList();
但這會在運行以下錯誤時引發例外:
The EntityType '*.customer' does not declare a navigation property with the name 'name'
我不明白,因為我的類遵循https://docs.microsoft.com/en-us/ef/ef6/fundamentals/relationships的形式,并且是通過Code First 從現有資料庫創建的。
public partial class deliveries
{
public int id { get; set; }
public int? amount { get; set; }
public int? customer_id { get; set; }
[ForeignKey("customer_id")]
public virtual customer customer { get; set; }
}
public partial class customer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public customer()
{
deliveries = new HashSet<deliveries>();
}
[Key]
public int customerID { get; set; }
[StringLength(50)]
public string name { get; set; }
[StringLength(10)]
public string address { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<deliveries> deliveries { get; set; }
}
uj5u.com熱心網友回復:
如果您只想顯示特定值,則必須進行自定義投影并通過Select. 它可以是 DTO 或匿名類,不需要包含。
var result = deliveries
.OrderBy(d => d.id)
.Select(d => new
{
d.customer.name,
d.customer.address
})
.ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/436555.html
上一篇:獲取陣列的最大值
