【问题标题】:Reading data from DB View从 DB View 读取数据
【发布时间】:2023-03-18 16:22:02
【问题描述】:

我是 asp.net MVC 的新手。我想从数据库视图中检索数据并将其映射到我的模型。模型类具有与视图相同的一组属性。有没有一种方法可以让我从 db 视图而不是表中获取数据(由于代码优先,表会自动创建)。

我的模型如下所示:

public class Product{

    public long ID { get; set; }

    [Display(Name = "Product Code")]
    public int ProductCode { get; set; }

    [Display(Name = "Product Title")]
    public string ProductTitle { get; set; }
};

public class ProductDBContext : DbContext
{
    public DbSet<Product> Products 
    { 
        get; set; }
}

【问题讨论】:

标签: c# asp.net-mvc entity-framework dbcontext


【解决方案1】:

您当然可以使用 Code First 来映射到视图,只需告诉 Code First 它是一个表,并且它将对视图使用与表相同的 SQL。显然,如果您尝试更新该实体,如果视图不可更新,您将收到异常。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    你在使用 dbml 吗?将你的 dbo.View 拖到 dbml 中,像使用表一样使用,但不能添加和更新。

    public class ProductDBContext : DbContext
    {
        public ProductDBContext ()
            : base("MyConnection") //web.config
        {
        }
    
        public DbSet<Product> Products { get; set; }
    }
    
    // Your View:
    // CREATE VIEW dbo.Product
    // AS
    // SELECT dbo.ProductProfile.ID, dbo.ProductProfile.ProductCode, dbo.ProductTitle.ProfileID, dbo.ProductTitle.ProductTitle 
    // FROM   dbo.ProductProfile INNER JOIN
    //          dbo.ProductTitle ON dbo.ProductProfile.ID = dbo.ProductTitle.ProfileID
    //
    [Table("dbo.Product")]  
    public class Product
    {
        [Key]
        public long ID { get; set; }
    
        [Display(Name = "Product Code")]
        public int ProductCode { get; set; }
    
        [Display(Name = "Product Title")]
        public string ProductTitle { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2020-06-23
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      相关资源
      最近更新 更多