我有兩個不同的課程:
以下是名為“附件”的資料庫表的模型:
namespace WebApi.Models
{
public class Attachment
{
public enum EntityType
{
Transaction
}
public int AttachmentId { get; set; }
public int EntityId { get; set; }
public EntityType Type { get; set; }
public string Filename { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
}
}
在我的 dbContext 類中,我有以下內容:
namespace WebApi.Models
{
public class accountingContext : DbContext
{
public DbSet<User>? Users { get; set; }
public DbSet<Transaction>? Transactions { get; set; }
public DbSet<Attachment>? Attachments { get; set; }
///...
}
}
然后我有一個與 Attachement 模型類似的 cvlass,它用于發送資料以回應 web api 請求,類如下:
namespace WebApi.Entities.AttachmentResponse;
public class AttachmentResponse
{
public int AttachmentId { get; set }
public string Filename { get; set; }
}
我希望讓我的班級分開回答,而不是因為我覺得不值得進入的原因而使用模型班級。
在對模型類執行查詢后,我需要轉換結果并映射到 AttachmentResponse 類。我正在嘗試以下操作:
List<WebApi.Entities.AttachmentResponse> attachments = (
from a in db.Attachments
from t in db.Transactions.Where(t => a.EntityId == t.TransactionId && t.UserId == userId)
where a.EntityId == EntityId
select new
{
a.AttachmentId,
a.Filename
}).ToList();
但是我在上述嘗試中遇到了錯誤。我也看過 ConvertAll ,但看不到如何在上面的代碼中使用它。
是否有可能完成我正在嘗試的事情?如果是這樣,我在哪里出錯了?
uj5u.com熱心網友回復:
您正在創建一個匿名型別的串列,而不是AttachmentResponse物件串列。您需要在投影中顯式創建它們:
select new AttachmentResponse
{
AttachmentId = a.AttachmentId,
Filename = a.Filename
}
我還會看看像 AutoMapper 這樣可以非常輕松地創建映射的工具,尤其是在屬性名稱相同的情況下。
uj5u.com熱心網友回復:
我不能發表評論,所以我不能問你遇到了什么錯誤。但是,從外觀上看,它似乎是一個鑄造問題。您可以將匿名型別轉換為其他型別。僅使用新品牌是匿名的,而不是指定它們型別您要宣告新品牌。
List<WebApi.Entities.AttachmentResponse> attachments = (
from a in db.Attachments
from t in db.Transactions.Where(t => a.EntityId == t.TransactionId && t.UserId == userId)
where a.EntityId == EntityId
select new WebApi.Entities.AttachmentResponse
{
a.AttachmentId,
a.Filename
}).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/511422.html
標籤:C#网
