How to create View (SQL) from Entity Framework in ABP Framework

笑着哭i 提交于 2019-12-24 18:13:05

问题


My situation is that I need to query from another database and show the result in my application. Both databases are on the same server. I came up with an idea on creating SQL-View in my database which would query the other database for values that I want. But I am not quite sure on how I can create or map SQL-View from the ABP framework?

I am using the full .Net framework with the Angular template.


回答1:


Creating View is not directly supported in EF. So you can try the below approach.

  • Create an empty Migration using Add-Migration.
  • Write you Create View script in Up method of generated migration and run the script using context.Database.ExecuteSqlCommand method.
  • Declare your class and use Table as you do for your model class.

[Table("YourViewName")] public class YourClassName {

}

  • Ignore your view class like this modelBuilder.Ignore<yourClassName>(); in OnModelCreating method.
  • Run Update-Database in Package Manager Console.



回答2:


Create your table view in the database. Then using EF FluentAPI to config the view mapping. Here is the sample code:

1. Create POCO class to map:

 public class YourView
 {
        public int Id { get; set; }

        public string Value { get; set; }
 }

2. EF FluentAPI mapping configuration:

Create map class:

 public class YourViewMap : IEntityTypeConfiguration<YourView>
 {
        public void Configure(EntityTypeBuilder<YourView> builder)
        {
            builder.ToTable("YourViewName");
        }
 }

Add mapping configuration to your DbContext (such as AbpCoreDbContext). Override OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new YourViewMap ());
    base.OnModelCreating(modelBuilder);
}

3. Get data:

using IRepository<YourView> to query data from the view.

P.S: related question how to use views in code first entity framework




回答3:


Create a new DbContext for your legacy database. You can have multiple DbContext in an ABP application. Each DbContext have its own connection string. Creating view is kinda hackish.



来源:https://stackoverflow.com/questions/49311461/how-to-create-view-sql-from-entity-framework-in-abp-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!