I have the following relationships:
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; }
}
And I end up with this query
_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);
I'd like to know if it is possible to replace some of the Include
/ ThenInclude
by a view using EF Core.
And if possible use it as
.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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.