1
我正在使用實體框架DB第一種方法。當我想拉從數據庫中的數據我使用的方法GetForm_AttachmentByAppID當我把這種方法從我的代碼。我得到以下運行時錯誤:實體或複雜類型'FPSDB_newModel.Form_Attachment'不能在LINQ to Entities查詢中構建
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: The entity or complex type 'FPSDB_newModel.Form_Attachment' cannot be constructed in a LINQ to Entities query.
public partial class Form_Attachment
{
public int Form_AttachmentID { get; set; }
public Nullable<int> AttachmentCategoryID { get; set; }
public int ApplicationID { get; set; }
public string EmployeeID { get; set; }
public string DocumentName { get; set; }
public string DocumentSize { get; set; }
public Nullable<byte> RoleID { get; set; }
public string Description { get; set; }
public Nullable<bool> SelectionForExtRev { get; set; }
public virtual Application Application { get; set; }
public virtual AttachmentCategory AttachmentCategory { get; set; }
public virtual Employee Employee { get; set; }
public virtual Role Role { get; set; }
}
上述文件是自動生成的,代碼位於FPSModel.cs下面是我的代碼來拉數據
public List<Form_Attachment> GetForm_AttachmentByAppID(int applicationID)
{
var context = new FPSDB_newEntities();
var data = (from f in context.Form_Attachment
where
(
f.ApplicationID== applicationID
)
select new Form_Attachment
{
Form_AttachmentID = f.Form_AttachmentID,
AttachmentCategoryID = f.AttachmentCategoryID,
EmployeeID = f.EmployeeID,
ApplicationID = f.ApplicationID,
DocumentName = f.DocumentName,
DocumentSize = f.DocumentSize,
RoleID = f.RoleID,
Description = f.Description,
SelectionForExtRev = f.SelectionForExtRev
}).ToList();
return data;
}
而且,這裏是我的表的數據庫定義Form_Attachments
CREATE TABLE [dbo].[Form_Attachment](
[Form_AttachmentID] [int] IDENTITY(1,1) NOT NULL,
[AttachmentCategoryID] [int] NULL,
[ApplicationID] [int] NOT NULL,
[EmployeeID] [varchar](10) NOT NULL,
[DocumentName] [nvarchar](500) NULL,
[DocumentSize] [nvarchar](50) NULL,
[RoleID] [tinyint] NULL,
[Description] [ntext] NULL,
[SelectionForExtRev] [bit] NULL,
CONSTRAINT [PK_Form_AttachmentID] PRIMARY KEY CLUSTERED
(
[Form_AttachmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
我已閱讀本The Projection should not be on to a mapped entity 所以,如果我做一類Form_Attachments1就像自動生成Form_Attachments所以會它是一個數據傳輸對象DTO,它是一個正確的方法。
完美解決方案!謝謝親愛的 – shomaail
我很高興我的幫助。 –
對於你剛剛注意到的其他問題,使用DTO類是一種更好的方法。我始終將DTO類用作數據訪問層和表示層之間的中間層(業務層)。這種方法爲我提供了靈活性,可以干擾驗證,日誌記錄或授權等數據。當然還有更多的好處,我不能在這裏全部寫出它們。好編碼:) –