在Entity Framework Core中使用SQL视图
例如,我有这样的模型:
public class Blog { public int BlogId { get; set; } public string Url { get; set; } public BlogImage BlogImage { get; set; } } public class BlogImage { public int BlogImageId { get; set; } public byte[] Image { get; set; } public string Caption { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } }
我想在ImageView视图中返回Url和Image 。
我在哪里需要创建和定义SQL视图?
在Entity Framework Core 2.1中,我们可以使用Yuriy N建议的查询类型 。
有关如何使用它们的更详细的文章可以在这里找到
根据文章的例子,最直接的方法是:
1.我们有以下实体模型来管理出版物
public class Magazine { public int MagazineId { get; set; } public string Name { get; set; } public string Publisher { get; set; } public List Articles { get; set; } } public class Article { public int ArticleId { get; set; } public string Title { get; set; } public int MagazineId { get; set; } public DateTime PublishDate { get; set; } public Author Author { get; set; } public int AuthorId { get; set; } } public class Author { public int AuthorId { get; set; } public string Name { get; set; } public List Articles { get; set; } }
2.我们有一个名为AuthorArticleCounts的视图,定义为返回作者编写的文章的名称和数量
SELECT a.AuthorName, Count(r.ArticleId) as ArticleCount from Authors a JOIN Articles r on r.AuthorId = a.AuthorId GROUP BY a.AuthorName
3.我们去创建一个用于View的模型
public class AuthorArticleCount { public string AuthorName { get; private set; } public int ArticleCount { get; private set; } }
4.我们在DbContext中创建一个DbQuery属性来使用Model中的视图结果
public DbQuery AuthorArticleCounts{get;set;}
5.最后,我们可以轻松地获得View的结果。
var results=_context.AuthorArticleCounts.ToList();
Entity Framework Core目前不支持视图。 请参阅https://github.com/aspnet/EntityFramework/issues/827 。
也就是说,您可以通过将实体映射到视图来欺骗EF使用视图,就像它是一个表一样。 这种方法有局限性。 例如,您无法使用迁移,您需要为我们手动指定EF的密钥,并且某些查询可能无法正常运行。 要绕过最后一部分,您可以手动编写SQL查询
context.Images.FromSql("SELECT * FROM dbo.ImageView")
EF Core不会在上下文calss中自动为SQL视图创建DBset,我们可以手动添加它们,如下所示。
public partial class LocalDBContext : DbContext { public LocalDBContext(DbContextOptions options) : base(options) { } public virtual DbSet YourView { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity (entity => { entity.HasKey(e => e.ID); entity.ToTable("YourView"); entity.Property(e => e.Name).HasMaxLength(50); }); } }
示例视图定义如下,几个属性
using System; using System.Collections.Generic; namespace Project.Entities { public partial class YourView { public string Name { get; set; } public int ID { get; set; } } }
在上下文类中为视图和数据库集添加类后,最好通过控制器中的上下文对象使用视图对象。
以下是在EF Core中使用SQL视图的新方法: 查询类型 。