我有一个SQL视图:
WITH DirectReports (ID,ParentFolderID, ParentFolderName,FolderID,FolderName,OwnerOCID,OwnerArName,OwnerEnName,FolderType,LEVEL)
AS
(
SELECT e.Id AS ID,cast(cast(0 AS binary) AS uniqueidentifier) AS ParentFolderID, cast('MainFolder - ' + MainFolders.enName AS nvarchar(250)) AS ParentFolderName,
e.Id AS FolderID, e.Name AS FolderName, WorkSpaces.Owner_Id AS OwnerOCID, OrgCharts.arName AS OwnerArName, OrgCharts.enName AS OwnerEnName,
MainFolders.Type AS FolderType, 0 AS LEVEL
FROM WorkSpaceFolders AS e INNER JOIN
MainFolders ON MainFolders.RootFolder_Id = e.Id INNER JOIN
WorkSpaces ON WorkSpaces.Id = MainFolders.WorkSpace_Id INNER JOIN
OrgCharts ON OrgCharts.Id = WorkSpaces.Owner_Id
WHERE e.Root = 1 AND e.Parent_Id IS NULL
UNION ALL
SELECT e.Id AS ID,e.Parent_Id AS ParentFolderID, d .FolderName AS ParentFolderName, e.Id AS FolderID, e.Name AS ChildFolderName, d .OwnerOCID, d .OwnerArName,
d .OwnerEnName, d .FolderType, LEVEL + 1
FROM WorkSpaceFolders AS e INNER JOIN
DirectReports AS d ON e.Parent_Id = d .FolderID)
SELECT *
FROM DirectReports
我正在使用代码首次迁移到我的数据库 - 如何将视图映射到以下实体?
public class UserFolders
{
public Guid ID { get; set; }
public Guid ParentFolderID { get; set; }
public string ParentFolderName { get; set; }
public Guid FolderID { get; set; }
public string FolderName { get; set; }
public Guid OwnerOCID { get; set; }
public string OwnerArName { get; set; }
public string OwnerEnName { get; set; }
public int FolderType { get; set; }
public int LEVEL { get; set; }
}
答案 0 :(得分:30)
视图可以映射为表格。它应该是这样的:
public class UserFoldersMap : EntityTypeConfiguration<UserFolders>
{
public UserFoldersMap()
{
this.ToTable("view_name");
this.HasKey(t => t.Id);
}
}
我希望能帮到你......
答案 1 :(得分:1)
我发现如果我的映射与我的视图不完全匹配,那么在尝试生成“表”时会出错,因为它认为它已经存在或与我的代码中的定义不匹配。
我在EF Power Tools中使用了逆向工程师代码优先功能,并复制了为我的视图生成的模型和模型Map文件。这些都没有问题。
然后,最后一步,我在你的DbContext中的OnModelCreation方法中添加了Map文件:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserFoldersMap());
}