我在數據庫Order和OrderDetails中有兩個表。我在Linq查詢中引用他們,但只從Orders表中提取數據。我也有一個對應的類 - ABOrders:Linq查詢並返回短日期格式的DateTime字段
[Table("[Order]")]
public partial class ABOrder
{
[Key]
public int OrderID { get; set; }
public string Field1 { get; set; }
public string Field2 { get; set; }
public DateTime OrderDate { get; set; }
}
的問題是,訂購日期帶有日期和時間,我只需要它作爲ShortDate格式的字符串。本來我已經試過:
var result = (from a in ctx.Order
join b in ctx.OrderDetails on a.OrderId Equals b.OrderId
where a.Field1.Equals(id) && b.Field1.Contains("TEST")
select new myClass.ABOrder
{
OrderId = a.OrderId,
Field1 = a.Field1,
Field2=a.Field2,
OrderDate = String.Format("MM/dd/yyyy", a.OrderDate)
};
但出錯了,所以我創建了一個新的類:
[Table("[Order]")]
public partial class CDOrder
{
[Key]
public int OrderID { get; set; }
public string Field1 { get; set; }
public string Field2 { get; set; }
public string OrderDate { get; set; }
}
,並嘗試了以下Linq查詢:
var result = (from a in ctx.Order
join b in ctx.OrderDetails on a.OrderId Equals b.OrderId
where a.Field1.Equals(id) && b.Field1.Contains("TEST")
select new myClass.ABOrder
{
OrderId = a.OrderId,
Field1 = a.Field1,
Field2=a.Field2,
OrderDate = a.OrderDate
}).AsEnumerable().Select(x => new myClass.CDOrder
{
OrderId = x.OrderId,
Field1 = x.Field1,
Field2=x.Field2,
OrderDate = String.Format("MM/dd/yyyy", x.OrderDate)
});
現在我得到錯誤:
The entity types 'ABOrder' and 'CDOrder' cannot share table 'Order' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
何我可以完成我想要的 - 從訂單表中檢索所有數據,但數據格式簡短?
P.S.在向用戶顯示數據時我無法進行任何調整,因此我必須在查詢中執行此操作。
你取回一個DateTime對象。當你真的想把它們顯示給用戶時,只需調用.ToString(「MM/dd/yyyy」) – Steve
我最初試圖做到這一點,但這是事實,當向用戶顯示時我無法做出任何調整 – ElenaDBA
Wouldn' t只是從CDOrder類中刪除屬性'[Table(「[Order]」)]'解決上述問題,還是需要將它識別爲DB的一部分才能使用? – starlight54