[英]EF Core Include a view
我有以下關系:
public class File
{
public string Path { get; set; }
}
public class Company
{
public string Name { get; set; }
}
public class Account
{
public int CompanyId { get; set; }
public Company Company { get; set; }
public int FileId { get; set; }
public File Avatar { get; set; }
}
public class Subject
{
public int AttachmentId { get; set; }
public File Attachment { get; set; }
}
public class Collaboration
{
public int SenderId { get; set; }
public Account Sender { get; set; }
public int ReceiverId { get; set; }
public Account Receiver { get; set; }
public int SubjectId { get; set; }
public Subject Subject { get; set; }
}
我最終得到了這個查詢
_dataContext
.Collaborations
.AsNoTracking()
.Include(x => x.Sender)
.ThenInclude(x => x.Company)
.Include(x => x.Sender)
.ThenInclude(x => x.Avatar)
.Include(x => x.Receiver)
.ThenInclude(x => x.Company)
.Include(x => x.Receiver)
.ThenInclude(x => x.Avatar)
.Include(x => x.Subject)
.ThenInclude(x => x.Attachment);
我想知道是否可以通過使用 EF Core 的視圖替換某些Include
/ ThenInclude
。
如果可能的話,用它作為
.Include(x => x.SenderAndCompanyInfo)
First create a sql view;
create view SenderAndCompany as
select s.Id,s.Name, s.SurName,c.CompanyName
from Sender s inner join Company c on c.Id = s.CompanyId
After creating sql view create model for it
public class SenderAndCompany
{
public int Id { get; set; }
public string Name { get; set; }
public string SurName { get; set; }
public string CompanyName { get; set; }
}
//Add to context
public DbSet<SenderAndCompany> SenderAndCompany { get; set; }
//map entity to view within the DbContext.OnModelCreating method
modelBuilder
.Entity<SenderAndCompany>()
.ToView(nameof(SenderAndCompany))
.HasKey(t => t.Id);
//Finally
_dataContext
.Collaborations
.AsNoTracking()
.Include(x => x.Sender)
.ThenInclude(x => x.SenderAndCompany)
.Include(x => x.Receiver)
.ThenInclude(x => x.Avatar)
.Include(x => x.Subject)
.ThenInclude(x => x.Attachment);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.