Working with SQL views in Entity Framework Core

后端 未结 6 2238
再見小時候
再見小時候 2020-11-30 03:07

For example, I have such model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public BlogImage BlogImage {         


        
6条回答
  •  -上瘾入骨i
    2020-11-30 03:32

    The EF Core doesn't create DBset for the SQL views automatically in the context calss, we can add them manually as below.

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

    The sample view is defined as below with few properties

    using System;
    using System.Collections.Generic;
    
    namespace Project.Entities
    {
        public partial class YourView
        {
            public string Name { get; set; }
            public int ID { get; set; }
        }
    }
    

    After adding a class for the view and DB set in the context class, you are good to use the view object through your context object in the controller.

提交回复
热议问题