2014-10-10 50 views
0

我遵循本教程(http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api)在我的ASP.NET Web应用程序中设置Web API。但是,它并没有讨论如何从数据库中检索记录。它不是硬编码哑数据到控制器,就像这样:从SQL DB获取数据用于ASP.NET Web窗体API

Product[] products = new Product[] 
    { 
     new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
     new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
     new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    }; 

比方说,我有我的SQL数据库的表称为“产品”,我怎么会在那里,而不是获取产品数据?如果有人能指出我的方向正确,我将不胜感激。

我曾尝试使用函数,但它没有工作。

DataTable dbProducts = new DataTable(); 
dbProducts = Wrapper.getProducts(); 
+0

首先你需要有一个数据库表并用它记录如果您对打想要从数据库中获取数据。其次,您需要添加数据访问层,以便查询数据库并获取所需的记录,以便Web API使用它们。 请按照本教程中的步骤进行操作,因为它显示了如何在Web API中使用实体框架:http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with -entity-framework/part-1 – 2014-10-10 16:09:56

回答

0

如果连接不工作检查出这个网站http://www.sqlstrings.com/ 和修改连接字符串到您想要的数据库类型。如果这是更多的学习经验,我建议你使用linq来sql或实体框架。

复制面食代码:

 // Create a connection to the database   
    SqlConnection conn = new SqlConnection("Data Source=MyDBServer;Initial Catalog=MyDB;Integrated Security=True"); 
    // Create a command to extract the required data and assign it the connection string 
    SqlCommand cmd = new SqlCommand("SELECT * FROM Product", conn); 
    cmd.CommandType = CommandType.Text; 
    // Create a DataAdapter to run the command and fill the DataTable 
    SqlDataAdapter da = new SqlDataAdapter(); 
    da.SelectCommand = cmd; 
    DataTable dt = new DataTable(); 
    da.Fill(dt); 
List<Product> products = new List<Product>(); 
foreach(DataRow row in dt.Rows) 
{ 
    products.add(New Product{ row["Id"], row["Name"], row["Category"], row["Price"]}); 
} 
+0

因此,在执行此操作后,如何将数据添加到产品数组中? – aberhamm 2014-10-10 16:42:57

+0

您可以遍历表的每一行并填充数组。 – Theyouthis 2014-10-10 17:55:20

+0

添加列表人口而不是数组,主要是因为我更喜欢列表。 – Theyouthis 2014-10-10 18:01:32

0

您可以使用实体框架+库从数据库中快速获取数据。

如果您已经在您的SQl数据库中有一个名为Product的表,请配置您的EF并在项目中提供所有EF参考。

我还没有看到的教程,但只给你一个快速和粗略的想法...

public class Product 
    { 
    public string Id {get;set;} 
    public Name {get;set;} 
    public string Category {get;set;} 
    public decimal Price {get;set;} 
    } 

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


    public class IProductRepository 
    { 
     public IQuerable<Product> Products{get;} 
    } 

    public class ProductRepository : IProductRepository 
    { 
    private AppContext context = new DBContext(); 

    public IQuerable<Product> Products 
    { 
     get 
    { 
    context.Products; 
    } 
    } 

    } 



    Now in your Web Api method & controller.... 


    public class ProductController 
    { 
    private IProductRepository repo; 

     public ProductController() 
    { 
     repo = new ProductRepository(); // or use DI 
    } 

    public List<Product> Get() 
    { 
    return repo.Products.ToList(); 
    } 

    }