這是我的兩個TABLE
我是採用code First來建立資料庫
這是相關的屬性
Categories
public class Categories
{
public Categories()
{
this.Products = new HashSet<Products>();
}
public int Id { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
public virtual ICollection<Products> Products { get; set; }
}
Products
public class Products
{
public Products()
{
this.OrderDetails = new HashSet<OrderDetails>();
}
[Key]
public int Id { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Name { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
public string Description { get; set; }
public int Category_Id { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
[Column(TypeName = "nvarchar(300)")]
public string PhotoUrl { get; set; }
[Column(TypeName = "nvarchar(150)")]
public string Author { get; set; }
[Column(TypeName = "nvarchar(50)")]
public string Publisher { get; set; }
public System.DateTime PublishDT { get; set; }
public bool IsPublic { get; set; }
public virtual Categories Categories { get; set; }
public virtual ICollection<OrderDetails> OrderDetails { get; set; }
}
這是我相關的查詢方法
public IEnumerable<Products> GetAll()
{
var query = (from x in _context.Products
join y in _context.Categories
on x.Category_Id equals y.Id
select x).ToList();
return query;
}
不知道為什麼
我的Categories是null
如果我改成這樣
public IEnumerable<Products> GetAll()
{
var query = (from x in _context.Products
join y in _context.Categories
on x.Category_Id equals y.Id
select x).ToList();
foreach(var dto in query)
{
dto.Categories = FindCategories(dto.Category_Id);
}
return query;
}
private Categories FindCategories(int category_Id)
{
return _context.Categories.Where(x => x.Id == category_Id).FirstOrDefault();
}
這樣反而能抓到
能否請問我錯在哪裡呢?
這是我建立的資料
更新
我好像找到原因了
我的外鍵好像是這個
想請問EFCORE那裏我該如何修改呢?
我的外鍵應該是要Category_Id才對
抱歉,我很少用code first所以問題稍微多一些也蠢一些QQ
再更
這個問題暫時用DTO處理掉
日後有機會我再回頭更新這個的解決辦法