问题
How can I use database views in Entity Framework?
I have the following view in the SQL database called pl
SELECT dbo.Product.Productkey,
dbo.Product.Productcode,
dbo.Product.Productname,
dbo.rcode.code,
dbo.rcode.label
FROM dbo.Product
INNER JOIN dbo.rcode
ON dbo.Product.programtypekey =
dbo.rcode.rcodekey
How can I read from the above view in application using EF? Currently I am readinmg from a table as shown below. I want to ready from view instead.
In my context, I have
public virtual DbSet<Product> Product { get; set; }
In Product
entity
namespace PDM.Core.App.Data.EF.Entity
{
public class Product : AuditableEntity<int>
{
public int ProgramTypeID { get; set; }
public string ProductCode { get; set; }
public string ProductName { get; set; }
}
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
public void Configure(EntityTypeBuilder<Product> Product)
{
if (Product == null)
throw new ArgumentNullException(nameof(Product));
Product.ToTable("Product");
Product.HasKey(nameof(Product.ID)).HasName("PK_Product");
Product.Property(p => p.ID)
.HasColumnName("ProductKey")
.HasColumnType("int");
Product.Property(p => p.ProgramTypeID)
.HasColumnName("ProgramTypeKey")
.HasColumnType("int")
.IsRequired(true);
Product.Property(p => p.ProductCode)
.HasColumnName("ProductCode")
.HasColumnType("varchar")
.HasMaxLength(15)
.IsRequired(true);
Product.Property(p => p.ProductName)
.HasColumnName("ProductName")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired(true);
}
}
error
回答1:
Firstly, You should create new ProductViewModel
to achieve it.
public class ProductViewModel
{
public string Productkey { get; set; }
public string Productcode { get; set; }
public string Productname { get; set; }
public string rCode {get; set;}
public string rLabel {get; set;}
}
Secondly, Use Join
to get 2 tables like below.
var result = await Context.Product.Join(Context.rcode, p => p.programtypekey, c => c.rcodekey, (product, rcode) =>
new ProductViewModel
{
Productkey = product.Productkey ,
Productcode = product.Productcode,
Productname = product.Productname,
rCode = rcode.Code,
rLabel = rcode.label ,
}
.AsNoTracking().ToListAsync();
If you want to get data from View, you can achieve it like this way
var result = await Context.Database.SqlQuery<ProductViewModel>("SELECT * FROM dbo.pl ").ToListAsync();
Read the reference from the following post
https://stackoverflow.com/a/18608759/9071943
来源:https://stackoverflow.com/questions/60348462/how-to-use-views-in-entity-framework