如何基于自定义Linq2Sql类创建强类型MVC视图

时间:2009-07-28 07:10:41

标签: asp.net-mvc linq-to-sql

我创建了一个自定义实体,因为我需要使用L2S中的连接填充一些实体。

当我右键单击Controller中的ActionResult代码以“添加视图”,然后选择“创建强类型视图”时,我的类不会显示在选择器中可用的类中。我不知道为什么。这是我的代码:

//The Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace FurnitureStore.Models.Repository
{
    public class FurnitureRepository
    {
        public IQueryable<Listing> GetProductListings()
        {
            FurnitureDataContext dc = new FurnitureDataContext();

        return (from p in dc.Products
                join c in dc.Categories
                on p.CategoryId equals c.CategoryId
                select new Listing
                {
                    ProductName = p.ProductName,
                    CategoryDescription = c.CategoryDescription
                });
    }
}
}

//The entity class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FurnitureStore.Models
{
    public class Listing
    {
        public string ProductName { get; set; }
        public string CategoryDescription { get; set; }
    }
}

//The Method in the Controller
public ActionResult ProductListings()
{
    FurnitureRepository fr = new FurnitureRepository();
    var listings = fr.GetProductListings();
    return View("ProductListings",listings);
}

2 个答案:

答案 0 :(得分:3)

确保编译代码,如果代码未编译,则新添加的类不会在选择器中可用的类中显示

答案 1 :(得分:1)

只需创建一个普通视图并自己编辑视图的页面定义(专门继承属性)。

<%@ Page ... Inherits="System.Web.Mvc.ViewPage<IQueryable<FurnitureStore.Models.Listing>>" %>

我无法回答为什么它没有出现在你的班级选择器中。

HTHS
查尔斯