0

私は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; }
}
4

2 に答える 2

0

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; }
}
于 2013-01-29T13:06:49.763 に答える
0

確かに Code First を使用してビューにマップできます。Code First に、それがテーブルであることを伝えるだけで、テーブルの場合と同じ SQL をビューに対して使用します。明らかに、そのエンティティを更新しようとすると、ビューが更新可能でない場合に例外が発生します。

お役に立てれば。

于 2013-01-29T12:57:14.833 に答える