I need to call 3 diferents views from my db context, but 3 views return sameview model.so how to declare 3 views and retund types in context class and onmodel builder creating.
public virtual DbSet
public virtual DbSet
public virtual DbSet
modelBuilder.Entity
modelBuilder.Entity
modelBuilder.Entity

Amit MohantyRank #112 · 20K reputationPosted Apr 24, 2023, 12:12 AM EDT
You cannot use the same entity type (
VwM) to map to multiple views in the sameDbContext. However, you can create a separate class for each view, even though they have the same model.public class View1M { // Properties that match the columns of View1 } public class View2M { // Properties that match the columns of View2 } public class View3M { // Properties that match the columns of View3 } public virtual DbSet View1 { get; set; } public virtual DbSet View2 { get; set; } public virtual DbSet View3 { get; set; } modelBuilder.Entity().ToView("View1"); modelBuilder.Entity().ToView("View2"); modelBuilder.Entity().ToView("View3");Tuhin PaulRank #7 · 71.9K reputationPosted Apr 23, 2023, 8:52 AM EDT
You cannot declare multiple DbSets with the same model type in your DbContext class as it will cause conflicts. Instead, you can create separate model classes for each view and map them accordingly in your DbContext's OnModelCreating method.
Tuhin PaulRank #7 · 71.9K reputationPosted Apr 23, 2023, 8:53 AM EDT
Part 1
Create separate model classes for each view:
public class View1Model { public int Id { get; set; } public string Name { get; set; } // Add other properties as needed } public class View2Model { public int Id { get; set; } public string Name { get; set; } // Add other properties as needed } public class View3Model { public int Id { get; set; } public string Name { get; set; } // Add other properties as needed }Tuhin PaulRank #7 · 71.9K reputationPosted Apr 23, 2023, 8:54 AM EDT
Part 2
In your DbContext class, create a DbSet for each view and map it to the corresponding model class:
public virtual DbSet View1 { get; set; } public virtual DbSet View2 { get; set; } public virtual DbSet View3 { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().ToTable("View1"); modelBuilder.Entity().ToTable("View2"); modelBuilder.Entity().ToTable("View3"); }Now you can query each view using the corresponding DbSet:
var view1Data = context.View1.ToList(); var view2Data = context.View2.ToList(); var view3Data = context.View3.ToList();