简体   繁体   English

EF Core 包含一个视图

[英]EF Core Include a view

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.我想知道是否可以通过使用 EF Core 的视图替换某些Include / ThenInclude

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM