EF core using views




To access database view using DbContext, you just need to :

1. POCO - Create your POCO using code shown below. Please note that you need to match exactly the POCO to your views but not necessary all the fields. Let's say you have 10 fields but you can just defined 3 that is of interest to you :

public partial class VwValuations
{
public string Instrument_Name { get; set; }
public int? InstrumentId { get; set; }
public int? PortfolioId { get; set; }
public decimal? Market_Value_Local_Discount { get; set; }
public DateTime? ValuationDate { get; set; }
}
}
view raw efviewpoco.cs hosted with ❤ by GitHub



2. Add your DbSet - You need to open up your DBContext and add in your DbSet Manually.


  public virtual DbSet VwValuations { get; set; }


3.OnModelCreating - in your DbContext, add your valuations data as shown below :


modelBuilder.Entity<VwValuations>(entity =>
{
entity.HasKey(e => e.InstrumentId);
entity.Property(e => e.InstrumentId)
.HasColumnName("InstrumentId")
.HasMaxLength(50);
entity.Property(e => e.Instrument_Name)
.HasColumnName("Instrument_Name")
.HasColumnType("nvarchar(4000)");
entity.Property(e => e.Market_Value_Local_Discount)
.HasColumnName("Market_Value_Local_Discount")
.HasColumnType("decimal(38, 5)");
entity.Property(e => e.PortfolioId)
.HasColumnName("PortfolioId")
.HasMaxLength(50);
entity.Property(e => e.ValuationDate)
.HasColumnName("ValuationDate")
.HasColumnType("datetime");
});


The data type used depends on your view.


That should be all the changes you need to make.


Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20